如何使用Gmail SMTP服务器在C#中邮寄?

Sam*_*Sam 5 c#

可能重复:
使用C#通过Gmail SMTP服务器发送电子邮件

对于使用C#进行邮寄并使用Gmail SMTP服务器,我们应该做些什么?因为在经过大量搜索之后我找到了一些方法来做到这一点,但结果却出现了失败异常.我想这是因为我没有为Gmail处理TSL(因为它适用于TSL),但我不知道如何使用C#来处理TSL.我非常感谢任何帮助或链接到有用的样本.这是我的代码:

public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}
Run Code Online (Sandbox Code Playgroud)

Zai*_*ikh 5

请尝试以下代码.这是我长期使用的工作代码.

    // Configure mail client (may need additional
    // code for authenticated SMTP servers).
    SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

    // Set the network credentials.
    mailClient.Credentials = new NetworkCredential("YourGmailEmail@gmail.com", "YourGmailPassword");

    //Enable SSL.
    mailClient.EnableSsl = true;

    // Create the mail message (from, to, subject, body).
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("zain.you2@gmail.com");
    mailMessage.To.Add(to);

    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;
    mailMessage.Priority = mailPriority;

    // Send the mail.
    mailClient.Send(mailMessage);
Run Code Online (Sandbox Code Playgroud)

参考:使用Gmail帐户发送电子邮件.


ala*_*a27 1

您应该告诉异常的消息。但是,是的,取消注释 emailClient.EnableSsl = true; 如果仍然无法正常工作,则您的防火墙或路由器可能阻止了端口。