轉貼:[ASP.net] 完整的Mail寄信功能 懶人Code分享
看到這個寫好的程式,讓我想了五分鐘,到底該不該拿過來用呢??最後決定還是copy過來用,因為真的太贊了。
/// <summary>
/// 完整的寄信功能
/// </summary>
/// <param name="MailFrom">寄信人E-mail Address</param>
/// <param name="MailTos">收信人E-mail Address</param>
/// <param name="Ccs">副本E-mail Address</param>
/// <param name="MailSub">主旨</param>
/// <param name="MailBody">信件內容</param>
/// <param name="isBodyHtml">是否採用HTML格式</param>
/// <param name="filePaths">附檔在WebServer檔案總管路徑</param>
/// <returns>是否成功</returns>
public bool Mail_Send(string MailFrom, string[] MailTos,string[] Ccs, string MailSub, string MailBody, bool isBodyHtml,string[] filePaths)
{
try
{
//防呆
if (MailFrom == "")
{
MailFrom = "sysadmin@system.com.tw";
}//命名空間: System.Web.Mail已過時,http://msdn.microsoft.com/zh-tw/library/system.web.mail.mailmessage(v=vs.80).aspx
//建立MailMessage物件
System.Net.Mail.MailMessage mms = new System.Net.Mail.MailMessage();
//指定一位寄信人MailAddress
mms.From = new MailAddress(MailFrom);
//信件主旨
mms.Subject = MailSub;
//信件內容
mms.Body = MailBody;
//信件內容 是否採用Html格式
mms.IsBodyHtml = isBodyHtml;if (MailTos !=null)//防呆
{
for (int i = 0; i < MailTos.Length; i++)
{
//加入信件的收信人(們)address
if (!string.IsNullOrEmpty(MailTos[i].Trim()))
{
mms.To.Add(new MailAddress(MailTos[i].Trim()));
}
}
}//End if (MailTos !=null)//防呆if (Ccs!=null) //防呆
{
for (int i = 0; i < Ccs.Length; i++)
{
if (!string.IsNullOrEmpty(Ccs[i].Trim()))
{
//加入信件的副本(們)address
mms.CC.Add(new MailAddress(Ccs[i].Trim()));
}
}
}//End if (Ccs!=null) //防呆if (filePaths!=null)//防呆
{//有夾帶檔案
for (int i = 0; i < filePaths.Length; i++)
{
if (!string.IsNullOrEmpty(filePaths[i].Trim()))
{
Attachment file = new Attachment(filePaths[i].Trim());
//加入信件的夾帶檔案
mms.Attachments.Add(file);
}
}
}//End if (filePaths!=null)//防呆
SmtpClient client = new SmtpClient("msa.hinet.net");//或公司、客戶的smtp_server
//以下可以省略,因為寄信不用帳密(除非客戶特別要求)
client.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["SMTPsendusername"],
WebConfigurationManager.AppSettings["SMTPsendpassword"]);client.Send(mms);//寄出一封信
return true;//成功
}
catch
{
return false;
}
}
使用方法:
//寄信人E-mail
string From_mail = "from_mail@hotmail.com";
//收信人E-mail
string[] to_emails = new string[] { @"to_email@hotmail.com", @"to_email2@hotmail.com" };
//副本
string[] to_cc = new string[] { @"to_email@hotmail.com", @"to_email2@hotmail.com" };
//主旨
string Subject = "我是主旨";
//內文
string htmlBody = TextBox1.Text.Trim().Replace(Environment.NewLine, "<br />");
//附檔在WebServer上的路徑
string[] filePaths = new string[] { @"D:\web\upload\xxx.xls", @"D:\web\upload\test.txt" };//寄信
bool sendResult = Mail_Send(From_mail, to_emails, to_cc, Subject, htmlBody, true, filePaths);
留言列表