通过SMTP客户端发送电子邮件失败,没有例外

时间:2015-09-23 07:57:54

标签: c# email smtp

我有简单的控制台应用程序,并尝试通过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());
        }
    }

至少可以得到异常吗?

2 个答案:

答案 0 :(得分:0)

请确保必须在发件人Gmail帐户中关闭2步验证。

如果两步验证仍然存在,那么它将无法与gmail服务器建立安全的SSL连接。

答案 1 :(得分:0)

我能看到代码中唯一缺少的内容如下:

public abstract class Repo {
    @CreateSqlObject
    abstract Dao dao(); // will return a jDBI managed DAO impl

    public void doWhatever() {
       /// logic
    }
}

将其添加到以下代码行上方:

#!/bin/bash
add () {
    sed -i~ -e '28 { s/= "\(.*\)"/= {"\1"}/; # Add curlies to a single entry.
                     s/}/,"'"$entry"'"}/     # Add the new entry.
                   }' "$file"
}

remove () {
    sed -i~ -e '28 { s/"'"$entry"'"//;      # Remove the entry.
                     s/,}/}/;               # Remove the trailing comma (entry was last).
                     s/{,/{/;               # Remove the leading comma (entry was first).
                     s/,,/,/;               # Remove surplus comma (entry was inside).
                     s/{"\([^,]*\)"}/"\1"/  # Remove curlies for single entry.
                   }' "$file"
}

if (( $# == 3 )) ; then
    file=$1
    action=$2
    entry=$3
    if [[ $action == add ]] ; then
        add
    elif [[ $action == remove ]] ; then
        remove
    fi
else
    echo "Usage: ${0#*/} file (add | remove) entry" >&2
    exit 1
fi

如果登录gmail时出现错误,则会抛出异常 - 请务必检查您的事件查看器,并确保没有一个空的catch块吞噬异常。

对于Gmail,没有必要指定client.UseDefaultCredentials = false; ,因为Google不允许模拟,因此会被忽略。