1

アプリケーションでは、単に送信するのではなく、SendAsync を使用する必要があります。だから私はクラスCEmailServerを作り、すべてをセットアップしました。これまでのところ Send は正常に動作しますが、SendAsync で動作するように変更すると動作しません。メールが送信され、userToken が配置されているときに呼び出されるメソッドを作成しましたが、失敗し続けます。エラーが見つかりません。これが私のコードです:

static bool mailSent = false;

//Method for Sending with attachment.
public void SendEmail(string Address, string Recipient, string Subject, string Body, string Dir)
{
    var fromAddress = new MailAddress("someadress.kimberley@gmail.com", "My Company");
    var toAddress = new MailAddress(Address, Recipient);
    const string fromPassword = "password";
    string subject = Subject;
    string body = Body;

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPassword)

    };
    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body,
    })
    {
        smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        string userState = "Test";
        message.Attachments.Add(new Attachment(Dir));
        smtp.SendAsync(message,userState);
        message.Dispose();
    }
}

//Method for Sending regular message without attachment.
public void SendEmail(string Address, string Recipient, string Subject, string Body)
{
    var fromAddress = new MailAddress("someadress.kimberley@gmail.com", "My Company");
    var toAddress = new MailAddress(Address, Recipient);
    const string fromPassword = "password";
    string subject = Subject;
    string body = Body;

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPassword)

    };
    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body,
    })
    {
        smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
        string userState = "Message Sent";
        smtp.SendAsync(message, userState);
        message.Dispose();
    }
}

//Method to be called when sending is complete
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
    // Get the unique identifier for this asynchronous operation.
    String token = (string)e.UserState;

    if (e.Cancelled)
    {
        MessageBox.Show("Sending Canc");
    }
    if (e.Error != null)
    {
        MessageBox.Show("Error Sending Mail");
    }
    else
    {
        MessageBox.Show("Message sent.");
    }
    mailSent = true;
}

どうもありがとうございました!

4

1 に答える 1