对于使用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)
请尝试以下代码.这是我长期使用的工作代码.
// 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帐户发送电子邮件.
| 归档时间: |
|
| 查看次数: |
1231 次 |
| 最近记录: |