C#通过smtp发送经过身份验证的邮件

时间:2017-04-28 07:32:23

标签: c# authentication smtp

我的sendmail脚本有点问题。我的邮件无法在我的某个内部分发列表中发送。我收到了返回的消息

RESOLVER.RST.AuthRequired; Authentication required

我的c#代码如下所示:

public void SendMail(int supplierValue, List<Location> locationList, string meldingsNr, string date, string fromT, string tillT)
    {
    var mailFrom = "mail@mail.com";
    SmtpClient client = new SmtpClient("server ip",25);
    client.UseDefaultCredentials = false;
    NetworkCredential basicAuthInfo = new NetworkCredential("username", "password");
    client.Credentials = basicAuthInfo;
    client.EnableSsl = false;

    // Create some empty vars

    var toList = "";
    var ccList = "";
    var mailSubject = "";
    var mailBody = "";
    List<string> locationListString = new List<string>();
    List<string> locationListString2 = new List<string>();

    // Populate toList with var llString

    ** code removed **

    // switch on supplier Value to fill toList, ccList and mailSubject

    ** code removed **

    // Create mail message

    MailMessage message = new MailMessage();
    MailAddress mailAddress = new MailAddress(mailFrom);
    message.To.Add(toList);
    message.From = mailAddress;
    message.CC.Add(ccList);

    // set subject and encoding

    message.Subject = mailSubject;
    message.SubjectEncoding = Encoding.UTF8;

    // set body and encoding

    message.Body = mailBody;
    message.BodyEncoding = Encoding.UTF8;
    message.IsBodyHtml = true;

    try
    {
        // Send mail 
        client.SendCompleted += (s, e) =>
        {
            client.Dispose();
            message.Dispose();
        };
        client.SendAsync(message, null);

    } catch (SmtpException ex)
    {
        MessageBox.Show(ex.InnerException.Message);

    } catch (System.Exception ex)
    {
       MessageBox.Show(ex.InnerException.Message);
    }
}

我应用了这个建议: How can I make SMTP authenticated in C#

确保在调用SmtpClient.UseDefaultCredentials = false后设置SmtpClient.Credentials。设置SmtpClient时,顺序很重要.UseDefaultCredentials = false会将SmtpClient.Credentials重置为null。

但这没有用。我的代码还有什么问题吗?

1 个答案:

答案 0 :(得分:0)

您可以将其用作电子邮件发送应用程序的更好选择:

    Let us suppose you are using OutLook to send the emails:
    SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", 587); // 587 is 
    the port number for outlook

    smtpClient.Credentials = new 
    System.Net.NetworkCredential("yourActualEmailIDhere", "yourActualPassword");
    smtpClient.UseDefaultCredentials = true;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.EnableSsl = true;
    MailMessage mail = new MailMessage();

    //Setting From , To and CC
    mail.From = new MailAddress("yourActualEmailIDhere");
    mail.To.Add(new MailAddress("destinationEmailAddress"));       // for 'To' you 
    don't need any password credentials. So relax.

   smtpClient.Send(mail);  // finally send the email

希望这会有所帮助。