为什么要用vs2008的Net.Mail发邮件呢?因为如果用CDO或其它方式发,在发图片的时候,图片在OUTLOOK可能不能正常显示(禁止从Inernet下截文件,必须手工设置图片才能正常显示).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//SendEmail();
// Response.Write("OK");
}
protected void Button1_Click(object sender, EventArgs e)
{
SendEmail();
Response.Write("send successfully!");
}
private void SendEmail()
{
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("test@163.com");
mail.To.Add("test@163.com");
mail.Bcc.Add("test@163.com");
//set the content
mail.Subject = "testing";
//first we create the Plain Text part
//AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
//to embed images, we need to use the prefix 'cid' in the img src value
//the cid value will map to the Content-Id of a Linked resource.
//thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'
string sHtml = "";
sHtml = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body lang=ZH-CN>";
sHtml = "test body
sHtml += "<a href='http://www.163.com/web/Xmas-2008/Xmas-Ecard-2008.html' target=_blank><img src=cid:companylogo2 border=0></a><br>";
sHtml += "<img src=cid:companylogo><br><br>";
sHtml += "测试<br>";
sHtml += "</body></html>";
//AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", null, "text/html");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(sHtml, null, "text/html");
//create the LinkedResource (embedded image)
LinkedResource logo = new LinkedResource("c://Inetpub//wwwroot//WebApplication1//A_IMG_5321-2.gif");//必须是本地的图片,不能写网址
LinkedResource logo2 = new LinkedResource("c://Inetpub//wwwroot//WebApplication1//ecard.bmp");
//LinkedResource logo = new LinkedResource(@"http://www.163.com/CNHK/images/roads-(1).jpg");
logo.ContentId = "companylogo";
logo2.ContentId = "companylogo2";
//add the LinkedResource to the appropriate view
htmlView.LinkedResources.Add(logo);
htmlView.LinkedResources.Add(logo2);
//add the views
mail.AlternateViews.Add(htmlView);
mail.Body = "";(//这句话一定要加上,不然中文会出现乱码)
//send the message
SmtpClient smtp = new SmtpClient("smtp.163.com"); //specify the mail server address
smtp.Credentials = new System.Net.NetworkCredential("user_name", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Timeout = 3600;
smtp.EnableSsl = false;
smtp.Send(mail);
}
}
}