用C#实现用免费smtp服务器(GMail)发邮件(转)

原文地址:http://www.cnblogs.com/skywind/archive/2007/09/21/901734.html

Method 1

--------------------------------------------------------------------------------------------------------

View Code
// using System.Net.Mail;
MailMessage message = new MailMessage();
message.From = new MailAddress("Sender@gmail.com""Your DisplayName"); // 发件人邮箱地址和显示名称
message.To.Add(new MailAddress("Recipients@gmail.com")); // 收件人地址,可以设置多个

message.Subject = "邮件标题" ;

message.Body = "邮件正文";

message .IsBodyHtml = false// 设置邮件正文是否为 html 格式的值
message .BodyEncoding = System.Text.Encoding.UTF8;  // 设置邮件正文编码
message .Priority = MailPriority.Normal; // 设置电子邮件的优先级

// 包含附件

string attachPath = "附件地址";

System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachPath); 

attachment.Name = System.IO.Path.GetFileName(attachPath); // 附件名称
attachment.NameEncoding = System.Text.Encoding.GetEncoding("gb2312"); // 附件名称的编码
attachment.TransferEncoding = System.Net.Mime.TransferEncoding.Base64; // 设置附件的编码
attachment.ContentDisposition.Inline = true;
attachment.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline;
string cid = attachment.ContentId; // 关键性的地方,这里得到一个id数值

message .Attachments.Add(attachment); // 可以添加多个附件

 

SmtpClient client = new SmtpClient();

client .Host = "smtp.gmail.com"// 设置 smtp 事务的主机名称或 IP 地址
client .Port = 587// 端口号

client.Credentials = new System.Net.NetworkCredential("Sender@gmail.com""mailbox password"); // Your mail address & password
client.EnableSsl = true// 经过ssl加密,gmail 邮箱必须设置为 ture

try
{
client.Send(message);
Response.Write("邮件发送到" + message.To.ToString() + "<br>");
}
catch (Exception ee)
{
Response.Write(ee.messageage + "<br>" + ee.InnerException.messageage);

Method 2
------------------------------------------------------------------------------------------------------

// http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

View Code
// using System.Net.Mail;
MailMessage message = new MailMessage();
message.From = new MailAddress("Sender@gmail.com"); 

message.To.Add(new MailAddress("Recipients@gmail.com")); 

message.Subject = "This is my subject"
message.Body = "This is the content"
SmtpClient client = new SmtpClient();
client.EnableSsl = true;  // 经过ssl加密,gmail 邮箱必须设置为 ture 

try
{
client.Send(message);
Response.Write("邮件发送到" + message.To.ToString() + "<br>");
}
catch (Exception ee)
{
Response.Write(ee.Message );
//In web.config

<system.net>
<mailSettings>
<smtp from="displayName<from@gmail.com>">
<network host="smtp.gmail.com" port="587" userName="Sender@gmail.com" password="your pwd" />
<!-- if has 'defaultCredentials="true"' , using Gmail can not send success -->
</smtp>
</mailSettings>
</system.net>

 

posted @ 2012-05-09 14:52  贝加  阅读(595)  评论(0编辑  收藏  举报