2010-11-30 67 views
5

可能重复:
Sending email through Gmail SMTP server with C#如何用C#与Gmail SMTP服务器邮件?

对于C#和使用Gmail的SMTP服务器的邮件有什么样的,我们应该做的一件棘手的事情?因为经过大量搜索,我找到了一些方法来做到这一点,但是我得到了一个失败例外。我想这是因为我不处理TSL for Gmail(因为它与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); 
} 
+0

让他问! :P – Seva 2010-11-30 12:51:57

+0

欢迎来到SO!这是一个很好的问题,你附上正确的代码。不过,之前也有类似的问题,请参阅上面的链接。这可能是你遇到特殊的例外;在这种情况下,如果您发布了例外的确切消息,人们可以更好地帮助您。 – Marijn 2010-11-30 13:04:26

回答

1

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

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("[email protected]", "YourGmailPassword"); 

    //Enable SSL. 
    mailClient.EnableSsl = true; 

    // Create the mail message (from, to, subject, body). 
    MailMessage mailMessage = new MailMessage(); 
    mailMessage.From = new MailAddress("[email protected]"); 
    mailMessage.To.Add(to); 

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

    // Send the mail. 
    mailClient.Send(mailMessage); 

参考:Sending Email using a Gmail Account

相关问题