使用MailMessage在C#中发送电子邮件

我在使用MailMessage发送电子邮件时遇到一些问题.我有两个电子邮件帐户(account1@gmail.com和account2@gmail.com),我希望account2能够通过按钮点击事件向帐户1发送电子邮件.

这就是我所拥有的,但它不起作用.我得到了例外并说这是禁止的.

            try
            {
                //do submit
                MailMessage emailMessage = new MailMessage();
                emailMessage.From = new MailAddress("account2@gmail.com", "Account2");
                emailMessage.To.Add(new MailAddress("account1@gmail.com", "Account1"));
                emailMessage.Subject = "SUBJECT";
                emailMessage.Body = "BODY";
                emailMessage.Priority = MailPriority.Normal;
                SmtpClient MailClient = new SmtpClient("smtp.gmail.com");
                MailClient.Credentials = new System.Net.NetworkCredential("account2@gmail.com", "password");
                MailClient.Send(emailMessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

我觉得这是Smtp的一个问题,但我不知道.

最佳答案
试试这个:

using (MailMessage emailMessage = new MailMessage())
{
    emailMessage.From = new MailAddress("account2@gmail.com", "Account2");
    emailMessage.To.Add(new MailAddress("account1@gmail.com", "Account1"));
    emailMessage.Subject = "SUBJECT";
    emailMessage.Body = "BODY";
    emailMessage.Priority = MailPriority.Normal;
    using (SmtpClient MailClient = new SmtpClient("smtp.gmail.com", 587))
    {
        MailClient.EnableSsl = true;
        MailClient.Credentials = new System.Net.NetworkCredential("account2@gmail.com", "password");
        MailClient.Send(emailMessage);
    }                               
} 

我将端口添加到smtp客户端并启用了SSL.
如果端口587不起作用,请尝试端口465.

转载注明原文:使用MailMessage在C#中发送电子邮件 - 代码日志