Asp.net 自动发送邮件的实例代码

发布时间:2019-11-25编辑:脚本学堂
本文介绍下,用asp.net在程序中实现自动发送邮件的一例代码,有需要的朋友,参考下吧。

一、配置web.config文件:
 

<system.net>
  <mailSettings>
    <smtp from="Emailname">
        <network host="smtp.jb200.com" userName="Emailname" password="Emailpassword"
        port="25" defaultCredentials="false"/>
    </smtp>
  </mailSettings>
</system.net>

二、发送邮件的函数:
 

复制代码 代码示例:
//// <summary>
/// 邮件发送方法(带附件)
/// </summary>
/// <param name="mailto">收件人地址。如:receiver@jb200.com</param>
/// <param name="mailsubject">邮件标题</param>
/// <param name="mailbody">邮件正文</param>
/// <param name="mailFrom">邮件发送人地址。如:sender@jb200.com</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);
    //如test@jb200.com,初步测试,用test@sina.com不行,用163的邮件服务器,就必须用163邮箱的用户名
    //收件人地址
    System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mailto);//如test@tom.com
    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))
{
  ...
  //发送成功
}
else
{
  ...
  //发送失败
  return;
}