简体   繁体   中英

Sending Email via GMail and .NET 4

Does .NET 4 has any problems in sending emails? I had a .NET 3.5 solution and it was working then migrated the solution to .NET 4 and It does not works; nothing changed!

Notes: I get this exception:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ...

And this is my code:

public static void SendEmail(
    this Email email)
{
    if (email.MailingSettings == null) throw new ArgumentNullException("email.MailingSettings", "specify email.MailingSettings");

    var settings = email.MailingSettings;

    if (string.IsNullOrEmpty(email.Sender)) throw new ArgumentException("email.Sender", "specify a sender");
    if (email.Recipients == null) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
    if (email.Recipients.Length == 0) throw new ArgumentNullException("email.Recipients", "specify at least a recipient");
    if (string.IsNullOrEmpty(settings.SMTPHost)) throw new ArgumentException("email.SMTPHost", "specify email.SMTPHost");

    var mail = new MailMessage();

    if (string.IsNullOrEmpty(email.SenderDisplayName))
        mail.From = new MailAddress(email.Sender);
    else
        mail.From = new MailAddress(email.Sender, email.SenderDisplayName);

    if (!string.IsNullOrEmpty(email.ReplyTo))
    {
        if (string.IsNullOrEmpty(email.ReplyToDisplayName))
        {
            mail.ReplyToList.Add(new MailAddress(email.ReplyTo));
        }
        else
        {
            mail.ReplyToList.Add(new MailAddress(email.ReplyTo, email.ReplyToDisplayName));
        }
    }

    foreach (string recipient in email.Recipients)
        mail.To.Add(new MailAddress(recipient));

    mail.Subject = email.Subject;
    mail.Body = email.Body;
    mail.IsBodyHtml = settings.IsBodyHtml;

    if (email.CC != null && email.CC.Length > 0)
        foreach (string cci in email.CC)
            mail.CC.Add(cci);

    if (email.BCC != null && email.BCC.Length > 0)
        foreach (string bcci in email.BCC)
            mail.Bcc.Add(bcci);

    if (email.Attachments != null)
        foreach (var ifn in email.Attachments)
            mail.Attachments.Add(
                new Attachment(
                    new MemoryStream(
                        ifn.Content),
                    ifn.FileName));

    var smtpPort = settings.SMTPPort > 0 ? settings.SMTPPort : 25;

    var smtpClient = new SmtpClient(settings.SMTPHost, smtpPort);
    smtpClient.EnableSsl = settings.EnableSsl;

    if (!string.IsNullOrEmpty(settings.SMTPUser))
    {
        smtpClient.UseDefaultCredentials = false;

        var smtpPassword = settings.SMTPPassword == null ? string.Empty : settings.SMTPPassword;

        NetworkCredential netCred;
        if (string.IsNullOrEmpty(settings.SMTPDomain))
            netCred = new NetworkCredential(settings.SMTPUser, smtpPassword);
        else
            netCred = new NetworkCredential(settings.SMTPUser, smtpPassword, settings.SMTPDomain);

        smtpClient.Credentials = netCred;
    }
    else
        smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;

    smtpClient.Timeout = 180 * 1000;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

    ServicePointManager.ServerCertificateValidationCallback =
        delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        { return true; };

    smtpClient.Send(mail);
}

如果所有内容符合所发布的代码和评论,那么我可以说您已对Google帐户启用了两步验证 ,在这种情况下,您需要生成“ 专用密码”。

This code is correct and works. The problem was on GMail side and solved (not detected why and how).

Try to use this :

try
{
    string smtpAddress = "smtp.gmail.com";
    int portNumber = 587;
    bool enableSSL = true;
    string emailFrom = "senderemail@gmail.com";
    string password = "password";
    string emailTo = "receiver@gmail.com";
    string subject = "Halo!";
    string body = "Halo, Mr. SMTP";
    MailMessage mail = new MailMessage();
    mail.From = new MailAddress(emailFrom);
    mail.To.Add(emailTo);
    mail.Subject = subject;
    mail.Body = body;
    mail.IsBodyHtml = true;

    using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
    {
        smtp.Credentials = new NetworkCredential(emailFrom, password);
        smtp.EnableSsl = enableSSL;
        smtp.Send(mail);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

*Note before that you need to activated this : https://myaccount.google.com/lesssecureapps

lesssecureapps

and then build and run the code.. it's amazing.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM