【发布时间】:2009-12-25 15:16:44
【问题描述】:
我有一个 Web 应用程序,我使用 MailHelper.cs 和 web.config 设置将其设置为通过 gmail 帐户自动发送电子邮件。我的应用程序已经工作了 10 天,现在它给了我错误并在发送电子邮件期间停止我处理了那个错误,它是“发送邮件失败”。内部异常是“尝试对无法访问的主机 216.239.59.109:587 执行套接字操作”这是代码:
<mailSettings>
<smtp from="myemail@gmail.com">
<network host="smtp.gmail.com"
port="587"
userName="myemail@gmail.com"
password="mypass"/>
</smtp>
</mailSettings>
using System.Net.Mail;
public class MailHelper
{
/// <summary>
/// Sends an mail message
/// </summary>
/// <param name="from">Sender address</param>
/// <param name="to">Recepient address</param>
/// <param name="bcc">Bcc recepient</param>
/// <param name="cc">Cc recepient</param>
/// <param name="subject">Subject of mail message</param>
/// <param name="body">Body of mail message</param>
public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body)
{
// Instantiate a new instance of MailMessage
MailMessage mMailMessage = new MailMessage();
// Set the sender address of the mail message
mMailMessage.From = new MailAddress(from);
// Set the recepient address of the mail message
mMailMessage.To.Add(new MailAddress(to));
// Check if the bcc value is null or an empty string
if ((bcc != null) && (bcc != string.Empty))
{
// Set the Bcc address of the mail message
mMailMessage.Bcc.Add(new MailAddress(bcc));
}
// Check if the cc value is null or an empty value
if ((cc != null) && (cc != string.Empty))
{
// Set the CC address of the mail message
mMailMessage.CC.Add(new MailAddress(cc));
} // Set the subject of the mail message
mMailMessage.Subject = subject;
// Set the body of the mail message
mMailMessage.Body = body;
// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal;
// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient();
mSmtpClient.Host = "smtp.gmail.com";
mSmtpClient.Port = 587;
mSmtpClient.EnableSsl = true;
// Send the mail message
mSmtpClient.Send(mMailMessage);
}
}
【问题讨论】:
-
当我需要 MailHelper 进行新项目时,我会一次又一次地回到这个问题。一个比答案更有帮助的问题。