asp.net 发送邮件 (system.web.mail Jmail)

时间:2022-09-24 08:46:53

asp.net webmail

<%@ page Language = "C#" debug = "true" Explicit="True" %>
<%@ Import Namespace = "System.Web.Util" %>
<%@ Import Namespace = "System.Web.Mail" %>
<script language = "C#" runat = "server">

public void SendMail (Object Obj, EventArgs E) {
labelSendMailResult.Text = "";
if (Page.IsValid) {
MailMessage mailObj = new MailMessage();

// 设置email的'from'和'to'的地址
mailObj.From = inputMailFrom.Value;
mailObj.To = inputMailTo.Value;

mailObj.Subject = inputMailSubject.Value;
mailObj.Body = textBoxMailBody.Text;

// 可选: 使用html格式的Email
mailObj.BodyFormat = MailFormat.Html;

// 可选: 对邮件进行加密
// mailObj.BodyEncoding = MailFormat.Base64;

// 可选: 设置邮件的优先级别为高
mailObj.Priority = MailPriority.High;

// 可选: 附件
if (inputMailAttachment.PostedFile.ContentLength > 0) {
// 注意这里我们创建了一个MailAttachment对象来附加一个文件到email。
mailObj.Attachments.Add(new MailAttachment(inputMailAttachment.PostedFile.FileName));
}

// 使用SmtpMail对象来发送邮件。
SmtpMail.Send(mailObj);
labelSendMailResult.Text = "邮件发送成功 From: " + inputMailFrom.Value + "; To: " + inputMailTo.Value;
if (inputMailAttachment.PostedFile.ContentLength > 0) {
labelSendMailResult.Text += "<br>该邮件包含附件: " + inputMailAttachment.PostedFile.FileName + ", 附件大小为: " + (inputMailAttachment.PostedFile.ContentLength / 1024).ToString() + " K Byte(s)";
}
}
}
</script>


<html>
<head>
<title>
发送邮件 ASP.NET</title>
</head>
<body>
<div align="center">
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#eeeeee" id="AutoNumber1">
<form id="formMail" method="post" action="" enctype="multipart/form-data" runat="server">
<tr>
<td width="20%" height="24">收件人地址: </td>
<td width="80%" height="24">
<input type="text" id="inputMailTo" name="inputMailTo" runat="server" size="48">
<asp:RequiredFieldValidator
id="RequiredFieldValidatorInputMailTo"
ControlToValidate="inputMailTo"
Display="Static"
EnableClientScript="False"
ErrorMessage="收件人不能为空"
runat="server"/>
<asp:RegularExpressionValidator id="RegularExpressionValidatorInputMailTo"
ControlToValidate="inputMailTo"
ValidationExpression="^[/w/.-]+@[/w/.-]+/.[a-zA-Z]+$"
Display="Static"
EnableClientScript="false"
ErrorMessage="收件人邮件地址错误"
runat="server"/>
</td>
</tr>
<tr>
<td width="20%" height="24">发件人地址: </td>
<td width="80%" height="24">
<input type="text" id="inputMailFrom" name="inputMailFrom" runat="server" size="48">
<asp:RequiredFieldValidator
id="RequiredFieldValidatorInputMailFrom"
ControlToValidate="inputMailFrom"
Display="Static"
EnableClientScript="False"
ErrorMessage="发件人不能为空"
runat="server"/>
<asp:RegularExpressionValidator id="RegularExpressionValidatorInputMailFrom"
ControlToValidate="inputMailFrom"
ValidationExpression="^[/w/.-]+@[/w/.-]+/.[a-zA-Z]+$"
Display="Static"
EnableClientScript="false"
ErrorMessage="发件人邮件地址错误"
runat="server"/>
</td>
</tr>
<tr>
<td width="20%" height="24">邮件主题: </td>
<td width="80%" height="24">
<input type="text" id="inputMailSubject" name="inputMailSubject" runat="server" size="48">
<asp:RequiredFieldValidator
id="RequiredFieldValidatorInputMailSubject"
ControlToValidate="inputMailSubject"
Display="Static"
EnableClientScript="False"
ErrorMessage="邮件主题不能为空"
runat="server"/>
</td>
</tr>
<tr>
<td width="20%" height="24">邮件内容:
</td>
<td width="80%" height="24">
<asp:TextBox id="textBoxMailBody" name="textBoxMailBody" runat="server" Rows="6" Cols="48" TextMode="MultiLine" />
<asp:RequiredFieldValidator
id="RequiredFieldValidatorTextBoxMailBody"
ControlToValidate="textBoxMailBody"
Display="Static"
EnableClientScript="False"
ErrorMessage="邮件内容不能为空"
runat="server"/>
</td>
</tr>
<tr>
<td width="20%" height="24">邮件附件:
</td>
<td width="80%" height="24">
<input type="file" id="inputMailAttachment" name="inputMailAttachment" runat="server" size="48">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="Send Mail" OnServerClick="SendMail" id="buttonSendMail" name="buttonSendMail" runat="server">
</td>
</tr>
<tr>
<td colspan="2" align="center" height="24">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Label id="labelSendMailResult" runat="server" text="" font-bold="True" forecolor="#FF0000"/>
</td>
</tr>
</form>
</table>
</div>
</body>
</html>

jmail

#region SendMail
  public string SendMail(string sBody,string sSubject,string sMailto,ArrayList aMailcc)
  {
   string sErrMessage="";
   string isSendMail=System.Configuration.ConfigurationSettings.AppSettings["isSendMail"];
       
   jmail.Message jmail= new jmail.MessageClass();

   //郵件格式txt或html
   jmail.ContentType = "text/html";
   jmail.Charset = "big5";
   jmail.ISOEncodeHeaders = true;
   //發送人郵件地址;
   jmail.From = "vtekmail@vtek.com.cn";   //  '改成管理員郵件;
   //發送人姓名;
   jmail.FromName = "WebMaster";
   //郵件主題
   jmail.Subject = sSubject;
   //身份驗證的用戶名;
   jmail.MailServerUserName = System.Configuration.ConfigurationSettings.AppSettings["mailUsername"];
   //用戶密碼
   jmail.MailServerPassWord = System.Configuration.ConfigurationSettings.AppSettings["mailPassword"];
   //添加收件人
   jmail.AddRecipient(sMailto.Trim(),sMailto.Trim(),null);
   for(int ic = 0;ic<aMailcc.Count;ic++)
   {
    jmail.AddRecipientCC(aMailcc[ic].ToString(),aMailcc[ic].ToString(),null);     //添加抄送人
   }
   //郵件內容
   jmail.Body = Server.UrlDecode(sBody);

   try
   {
    if(isSendMail.ToLower()=="true")
    {
     jmail.Send(System.Configuration.ConfigurationSettings.AppSettings["mailServer"],false);
     //'清除資源
     //jmail.Close();
    }
   }
   catch(Exception ex)
   {
    sErrMessage="郵件傳送失敗:" + ex.Message ;
   }

   return sErrMessage;

  }

  public string SendMail(string sBody,string sSubject,ArrayList aMailto,ArrayList aMailcc)
  {
   string sErrMessage="";
   string isSendMail=System.Configuration.ConfigurationSettings.AppSettings["isSendMail"];
       
   jmail.Message jmail= new jmail.MessageClass();

   //郵件格式txt或html
   jmail.ContentType = "text/html";
   jmail.Charset = "big5";
   jmail.ISOEncodeHeaders = true;
   //發送人郵件地址;
   jmail.From = "webmaster@slivertek.com";   //  '改成管理員郵件;
   //發送人姓名;
   jmail.FromName = "WebMaster";
   //郵件主題
   jmail.Subject = sSubject;
   //身份驗證的用戶名;
   jmail.MailServerUserName = System.Configuration.ConfigurationSettings.AppSettings["mailUsername"];
   //用戶密碼
   jmail.MailServerPassWord = System.Configuration.ConfigurationSettings.AppSettings["mailPassword"];
   //添加收件人
   for(int ic = 0;ic<aMailto.Count;ic++)
   {
    jmail.AddRecipient(aMailto[ic].ToString(),aMailto[ic].ToString(),null);     //添加收件人
   }

   for(int ic = 0;ic<aMailcc.Count;ic++)
   {
    jmail.AddRecipientCC(aMailcc[ic].ToString(),aMailcc[ic].ToString(),null);     //添加抄送人
   }
   //郵件內容
   jmail.Body = Server.UrlDecode(sBody);

   try
   {
    if(isSendMail.ToLower()=="true")
    {
     jmail.Send(System.Configuration.ConfigurationSettings.AppSettings["mailServer"],false);
     //'清除資源
     jmail.Close();    
    }
   }
   catch(Exception ex)
   {
    sErrMessage="郵件傳送失敗:" + ex.Message ;
   }

   return sErrMessage;

  }

  public string SendMail(string sBody,string sSubject,string sMailto)
  {
   ArrayList aMailcc =new ArrayList();
   return SendMail(sBody,sSubject,sMailto,aMailcc);
  }
  ///   <summary>
  ///   發送郵件
  ///   </summary>
  ///   <param   name="userName">驗證用戶名</param>
  ///   <param   name="password">密碼</param>
  ///   <param   name="serverName">伺服器</param>
  ///   <param   name="mailHeader">郵件頭</param>
  ///   <param   name="mailType">郵件類型   Text/HTML</param>
  ///   <param   name="textBody">郵件文本正文</param>
  ///   <param   name="htmlBody">郵件HTML正文</param>
  ///   <param   name="subject">郵件主題</param>
  ///   <param   name="setTime">定時發送時間</param>
  ///   <param   name="accept">接受者郵箱</param>
  ///   <param   name="bcc">密送人</param>
  ///   <param   name="cc">暗送人集合</param>
  ///   <param   name="sendLevel">發送級別</param>
  ///   <param   name="encoding">編碼方式</param>
  ///   <param   name="isFeedBack">對方讀到信是否回復</param>
  ///   <param   name="dsAttach">郵件附件集合</param>
  ///   <param   name="charType">設置郵件使用的字元集   中國默認為[GB2312]</param>
  ///   <returns>成功標志</returns>

  public   bool   SendMail(string userName,string password,string serverName,
   string   mailHeader,string mailType,   string textBody,
   string htmlBody,   string subject,   string setTime,
   ArrayList accept, ArrayList bcc, ArrayList cc,
   int sendLevel, string encoding,   bool isFeedBack,
   string charType,DataSet dsAttach)
  {
   jmail.Message msg = new jmail.MessageClass();
   msg.Logging = true;                          //身份驗證
   msg.Silent = true;          
   msg.AddHeader(mailHeader,mailHeader);         //添加郵件頭
   msg.ContentType = "multipart/mixed";          //郵件類型   HTML格式/純文本格式     multipart/alternative/mixed/related  
   msg.Encoding = "Base64";                      //設置附件的默認編碼:Base64或Quoted-Printable  
   msg.Charset = "GB2312";                       //設置郵件使用的字元集。默認為US-ASCII,支援中文則設置為GB2312。
   msg.ContentTransferEncoding = "Base64";       //設置郵件編碼。默認為:Quoted-Printable
   msg.Priority = (byte)sendLevel;               //郵件發送級別
   msg.MailServerUserName = userName;            //驗證用戶名
   msg.MailServerPassWord = password;            //驗證密碼
   msg.From = userName;                          //來自于

   msg.Subject = subject;                        //郵件主題
   msg.Body = textBody;                          //純文本正文
   msg.HTMLBody = htmlBody;                      //HTML格式正文
   for(int i = 0;i<accept.Count;i++)
   {
    msg.AddRecipient(accept[i].ToString(),accept[i].ToString(),null);     //添加接收人郵箱位址
   }
   for(int ib = 0;ib<bcc.Count;ib++)
   {
    msg.AddRecipientBCC(bcc[ib].ToString(),null);     //添加密送人
   }
   for(int ic = 0;ic<cc.Count;ic++)
   {
    msg.AddRecipientCC(cc[ic].ToString(),cc[ic].ToString(),null);     //添加抄送人
   }
   msg.ReturnReceipt = isFeedBack;         //對方收到郵件是否回復

   if(setTime != null)
   {
    if(setTime.Length == 20)
     msg.DeferredDelivery = Convert.ToDateTime(Convert.ToDecimal(setTime));
   }

   //
   //添加附件
   //
   if(dsAttach != null)
   {
    for(int index = 0;index<dsAttach.Tables[0].Rows.Count;index ++)
    {
     msg.AddAttachment(dsAttach.Tables[0].Rows[index]["FILE_PHYPATH_ATTACH"].ToString(),false,"");
    }
   }

   try
   {
    if(msg.Send(serverName,false))
    {
     return true;
    }
    else
    {
     return false;
    }
   }
   catch
   {
    return false;
   }
  }

  #endregion