2011/02/10

使用 DotnetOpenMail發送附帶檔案的信件

主要目的是想使用DotnetOpenMail發送附帶檔案的信件,而附帶的文件是由GridView轉成Excel格式,試了許多google大神提供的方法,和我自己亂TRY之後,終於得到我要的結果了....

1.將GridView資料導入Excel:EnableEventValidation="false",加入事件,不然RenderControl會出現錯誤"control 'maincontent_gridview1' of type 'gridview' must be placed inside a form tag with runat=server."

public override void VerifyRenderingInServerForm(Control control){//base.VerifyRenderingInServerForm(control);}

參考 http://www.cnblogs.com/xugang/archive/2007/09/14/892977.html



2.用DotnetOpenMail附帶Excel檔案寄出至指定信箱
參考 http://www.cnblogs.com/zhifengwu1211/archive/2007/01/25/630713.html


private string GridViewToHtml(GridView gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}

private void SentMail()
{
string main = GridViewToHtml(GridView1);
string title = "SERVER BACKUP RECORD - " + DateTime.Now;
string email = "@mailaddress";
EmailMessage emailMessage = new EmailMessage();
emailMessage.HeaderCharSet = System.Text.Encoding.UTF8;
emailMessage.FromAddress = new EmailAddress("@mailaddress");
SmtpServer smtpServer = new SmtpServer("xxx.xxx.xxx.xxx");
smtpServer.SmtpAuthToken = new SmtpAuthToken("@account", "@password");
emailMessage.ContentType = "TEXT/HTML";
emailMessage.Subject = title;

emailMessage.HtmlPart = new HtmlAttachment("test");
emailMessage.HtmlPart.CharSet = System.Text.Encoding.UTF8;

Byte[] fileBytes = Encoding.Default.GetBytes(main);
FileAttachment fileAttachment = new FileAttachment(fileBytes);
fileAttachment.FileName = title + ".xls";
fileAttachment.ContentType = "application/vnd.ms-excel";
emailMessage.AddMixedAttachment(fileAttachment);

emailMessage.AddToAddress(new EmailAddress(email));
emailMessage.Send(smtpServer);
}

沒有留言:

張貼留言