我有简单的控制台应用程序,并尝试通过 C# 中的 SMTP 类发送邮件,但没有发送邮件,应用程序已关闭,也没有抛出异常。问题线是 client.Send(msg).
using (var client = new SmtpClient()) {
client.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = True;
client.Timeout = 20000;
client.Credentials = new NetworkCredential(@ConfigurationManager.AppSettings["senderEmailAddress"].ToString(),@ConfigurationManager.AppSettings["senderEmailPassword"].ToString());
client.Host = "smtp.gmail.com;"
using (var msg = new MailMessage()) {
msg.From = new MailAddress(@ConfigurationManager.AppSettings["senderEmailAddress"].ToString());
msg.Sender = new MailAddress(@ConfigurationManager.AppSettings["senderEmailAddress"].ToString());
msg.Subject = fileName;
msg.Attachments.Add(new Attachment(OutputFilePath));
msg.To.Add(EmailAddress);
client.Send(msg); }}
private void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e) {
if (e.Cancelled == true || e.Error != null) {
throw new Exception(e.Cancelled ? "EMail sedning was canceled." : "Error: " + e.Error.ToString());
}
}
至少有可能获得例外吗?
请确保必须在发件人 Gmail 帐户中关闭两步身份验证。
如果两步身份验证保持打开状态,则它将无法与 gmail 服务器建立安全的 SSL 连接。
我唯一能看到您的代码中缺少的内容如下:
client.UseDefaultCredentials = false;
将其添加到以下代码行上方:
client.Credentials = new NetworkCredential(@ConfigurationManager.AppSettings["senderEmailAddress"].ToString(),@ConfigurationManager.AppSettings["senderEmailPassword"].ToString());
如果登录 gmail 时出现错误,则会引发异常 - 请务必检查事件查看器并确保没有空的 catch 块来吞噬异常。
对于 gmail,没有必要指定
msg.From
,因为 google 不允许冒充,因此它将被忽略。