自动发送邮件

一、首先需要配置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">收件人地址。如:mailto:receiver@163.com%3C/param>
    /// <param name="mailsubject">邮件标题</param>
    /// <param name="mailbody">邮件正文</param>
    /// <param name="mailFrom">邮件发送人地址。如:mailto:sender@163.com%3C/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@163.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))
...{
  ShowAndRedirect(this, "注册确认函已经发送到你的邮箱,请查收!", "index.aspx");
}
else
...{
   ShowAndRedirect(this, "邮件发送失败!", "index.aspx");
   return;
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/h1jie/archive/2008/01/21/2057212.aspx

posted @ 2010-05-18 14:29  你妹的sb  阅读(309)  评论(0编辑  收藏  举报
百度一下