ITPub博客

首页 > 应用开发 > IT综合 > .net System.Web.Mail发送邮件的实际应用代码

.net System.Web.Mail发送邮件的实际应用代码

原创 IT综合 作者:yuzhangqi 时间:2008-12-17 10:06:23 0 删除 编辑

本实例代码实现:

1. 构造一个EmailMessage对象实例;

2. 读取配置文件的邮件发送设置,如SMTP Server, UserName,Password,是否需要验证;

3. 异常处理;

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mail;
using System.IO;

namespace Service.MailService
{
///


/// 邮件发送器。
///

public class EmailSender
{
///
/// 执行Email发送动作
///

///
private void Send(EmailMessage item)
{
MailMessage mail = new MailMessage();
mail.From = item.From;
mail.To = item.To;
mail.Subject = item.Subject;
mail.Body = item.Message;
mail.BodyFormat = MailFormat.Html;

if (mail.To.Equals(string.Empty) || (!Validator.CheckEmailAddress(mail.To)))
{
throw new Exception("无效的邮件地址。");
}

bool needAuthenticeate = Convert.ToBoolean(ConfigReader.GetValueByKeyFromConfigFile("NeedAuthenticate"));
if (needAuthenticeate)
{
string userName = ConfigReader.GetValueByKeyFromConfigFile("AuthorizedUser");
string password = ConfigReader.GetValueByKeyFromConfigFile("AuthorizedPassword");

mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1"); //basic authentication
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName); //set your username here
mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); //set your password here
}

string file = item.Attachment;
try
{
if (File.Exists(file))
{
MailAttachment attachment = new MailAttachment(file,MailEncoding.Base64);
mail.Attachments.Add(attachment);
}

SmtpMail.SmtpServer = ConfigReader.GetValueByKeyFromConfigFile("SmtpServer");
SmtpMail.Send(mail);
}
catch (Exception ex)
{
throw new Exception("邮件发送中出现异常,请联系邮件服务器管理员。",ex);
}
}

}
}

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/13651903/viewspace-1014817/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-06-10

  • 博文量
    102
  • 访问量
    763296