我有簡單的控制檯應用程序,並試圖通過C#中的SMTP類發送郵件,但沒有發送郵件,應用程序已關閉,也沒有引發異常。問題行是client.Send(msg)。通過SMTP客戶端發送電子郵件失敗,沒有例外
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帳戶以允許外部連接? – acostela
我不確定你的意思,但我在智能手機或Outlook中使用此帳戶。 – petrppe
這在早些時候在SO中得到了回答。 [http://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail](http://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail) –