无法在mvc应用程序中发送电子邮件

时间:2014-03-15 18:51:29

标签: c# asp.net-mvc email smtp

从我的应用程序发送电子邮件时遇到一些麻烦..

我得到以下例外

An exception of type 'System.Net.Mail.SmtpException' occurred in System.dll but was not handled in user code

Additional information: Failure sending mail.

运行时弹出异常:smtpClient.Send(mailMessage);

应发送邮件的功能:

public static void SendEmail(string toAddress, string subject, string body, bool isBodyHtml = true)
{
    var mailMessage = new MailMessage();
    mailMessage.To.Add(toAddress);
    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;

    var smtpClient = new SmtpClient { EnableSsl = false };
    smtpClient.Send(mailMessage);
}

WebConfig配置

 <system.net>
    <mailSettings>
      <!-- Method#1: Send emails over the network -->
      <smtp deliveryMethod="Network" from="myusername@gmail.com">
        <network host="gmail.com" userName="myusername"  password="mypw"  port="465" />
      </smtp>
    </mailSettings>
  </system.net>

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:3)

这就是我发送gmail的方式:

    static void SendMail(string sSubject, string sBody)
    {
        const string senderID = "ImTheSender@gmail.com"; // use sender's email id here..
        const string toAddress = "ImTheRecip@gmail.com";
        const string senderPassword = "passwords are fun"; // sender password here...
        try
        {
            SmtpClient smtp = new SmtpClient
            {
                Host = "smtp.gmail.com", // smtp server address here...
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
                Timeout = 30000,
            };
            MailMessage message = new MailMessage(senderID, toAddress, sSubject, sBody);
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            LogThis("Error sending mail:" + ex.Message);
            Console.ResetColor();
        }
    }