简体   繁体   中英

Emailing from Gmail error on DisplayName property

Bellow is my code when i remove DisplayName Property of MailAddress() it work fine but Receiving end mail show EmailID on Display Name like emailID@gmail.com.

MailMessage mail = new MailMessage();
    mail.From = new System.Net.Mail.MailAddress("emailID@domainName.com");
    // The important part -- configuring the SMTP client
    SmtpClient smtp = new SmtpClient();
    smtp.Port = 587;   // [1] You can try with 465 also, I always used 587 and got success
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
    smtp.UseDefaultCredentials = false; // [3] Changed this
    smtp.Credentials = new NetworkCredential(mail.From.ToString(), "password");  // [4] Added this. Note, first parameter is NOT string.
    smtp.Host = "smtp.gmail.com";
    mail.IsBodyHtml = true;
    mail.Subject = Subject;
    mail.Body = Body;
    mail.To.Add(new MailAddress(To));
    smtp.Send(mail);
    mail.Dispose();

When i add Display name of MailAddress() i receive this error message.

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.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at ***

Where i am wrong?

var client = new SmtpClient
    {
     Host = "smtp.googlemail.com",
     Port = 587,
     UseDefaultCredentials = false,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     EnableSsl = true,
     Credentials = new NetworkCredential(SmtpUserName, SmtpUserPassword);
    };

client.Send(mail);

where mail is an instance of MailMessage

private static SecureString _smtpPassword;

    public static SecureString SmtpUserPassword
    {
        get
        {
            if (_smtpPassword != null)
                return _smtpPassword;

            _smtpPassword = new SecureString();

            foreach (var c in "your password here")
                _smtpPassword.AppendChar(c);

            _smtpPassword.MakeReadOnly();

            return _smtpPassword;
        }
    }

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