发送Outlook地址为C#的电子邮件?

时间:2014-08-22 15:00:22

标签: c# email outlook smtp sendmail

我想发送带有Outlook地址的电子邮件,如果我想简单地发送Outlook,我需要在导航器中输入url,例如' mail.xxx.com',然后Outlook网络应用显示,我输入用户名/域名和密码,所以我想在C#中这样做,这是代码:

string client_Host = "";
int client_Port = 0;

if (cmb_Destinataire.Text.ToLower().Contains("hotmail"))
{
    client_Host = "smtp.live.com";
    client_Port = 465;
}
else if (cmb_Destinataire.Text.ToLower().Contains("gmail"))
{
    client_Host = "smtp.gmail.com";
    client_Port = 587;
}
MailMessage msg = new MailMessage(cmb_De.Text, cmb_Destinataire.Text.Trim(), txt_Objet.Text, txtDescription.Text);

SmtpClient client = new SmtpClient(client_Host, client_Port);
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("username", "password","domaine");
client.SendAsync(msg,"test");

MessageBox.Show("sent", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Information);

但我没有收到任何电子邮件。

1 个答案:

答案 0 :(得分:0)

client.SendAsync(msg,"test");是一种异步方法。所以它后面的消息框不会告诉你电子邮件真的被发送了。消息框将以任一方式触发。你可能错过了另一个线程抛出的异常 考虑实施以下回调:

private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
             String token = (string) e.UserState;

            if (e.Cancelled)
            {
                 Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                 Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            } else
            {
                Console.WriteLine("Message sent.");
            }
        }

并且不要忘记注册你的回调

client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);