在.Net C#中通过Gmail发邮件

本文来自stackoverflow.com, http://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail

这个不是通过自有的主机向外发邮件,而是在网站中,通过一个指定的Gmail账号发出邮件。注意端口号是587,不要改变为Outlook设置时用的465。

using System.Net.Mail;
using System.Net;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

 

posted @ 2014-02-24 21:52  wusir  阅读(174)  评论(0编辑  收藏  举报