今天有一個模塊需要自動發送郵件的功能,就隨便寫了一個,記錄一下作為積累。
一、首先需要配置web.config文件:
<system.Net>
<mailSettings>
<smtp from="Emailname">
<network host="smtp.163.com" userName="Emailname" password="EmailpassWord"
port="25" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.Net>二、然後編寫發送郵件的函數:
/**//// <summary>
/// 郵件發送方法(帶附件)
/// </summary>
/// <param name="mailto">收件人地址。如:[email protected]</param>
/// <param name="mailsubject">郵件標題</param>
/// <param name="mailbody">郵件正文</param>
/// <param name="mailFrom">郵件發送人地址。如:[email protected]</param>
/// <param name="list">附件路徑</param>
/// <returns></returns>
public bool MySendMail(string mailto, string mailsubject, string mailbody, string mailFrom, ArrayList list)
...{
try
...{
//郵件發送人地址
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(mailFrom);
//如
[email protected],初步測試,用
[email protected]不行,用163的郵件服務器,就必須用163郵箱的用戶名
//收件人地址
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mailto);//如
[email protected] System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);
mail.Subject = mailsubject;
mail.Body = mailbody;
//以下設置服務器
System.Net.Mail.SmtpClIEnt mySmth = new System.Net.Mail.SmtpClIEnt();
//以下為增加附件
int count = list.Count;
for (int i = 0; i < count; i++)
...{
System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(list[i].ToString());
mail.Attachments.Add(data);
}
mySmth.Send(mail);
mail.Dispose();
return true;
}
catch
...{
return false;
}
}
三、最後就是對函數的調用了:
//自動發送郵件
string mailSubject = "會員注冊確認函";
string mailBody = "正文內容。";
string mailFrom = ConfigurationManager.APPSettings["SendMail"];
ArrayList List = new ArrayList();
List.Add(Server.MapPath(ConfigurationManager.APPSettings["SendMailText"]));
if (MySendMail(this.txtEmail.Text, mailSubject, mailBody, mailFrom, List))
...{
ShowAndRedirect(this, "注冊確認函已經發送到你的郵箱,請查收!", "index.ASPx");
}
else
...{
ShowAndRedirect(this, "郵件發送失敗!", "index.ASPx");
return;
}