1、获取table的HTML内容(这样就有格式和内容了),为发送邮件内容做准备,就是mailmessage的body内容;
2、获取填报用户的邮箱地址
3、调用封装的发邮件类进行发送,但之前必须有授权的发件人票据。
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; namespace SendMailHelper { public class SendMail { private MailMessage mailMessage; private SmtpClient smtpClient; private string password;//发件人密码 /// <summary> /// 处审核后类的实例 /// </summary> /// <param name="To">收件人地址</param> /// <param name="From">发件人地址</param> /// <param name="Body">邮件正文</param> /// <param name="Title">邮件的主题</param> /// <param name="Password">发件人密码</param> public SendMail(string[] To, string From, string Body, string Title, string Password) { mailMessage = new MailMessage(); foreach (var item in To) { mailMessage.To.Add(item); } mailMessage.From = new System.Net.Mail.MailAddress(From); mailMessage.Subject = Title; mailMessage.Body = Body; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.Priority = System.Net.Mail.MailPriority.Normal; this.password = Password; } /// <summary> /// 添加附件 /// </summary> public void Attachments(string Path) { string[] path = Path.Split(','); Attachment data; ContentDisposition disposition; for (int i = 0; i < path.Length; i++) { data = new Attachment(path[i], MediaTypeNames.Application.Octet);//实例化附件 disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);//获取附件的创建日期 disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);//获取附件的修改日期 disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);//获取附件的读取日期 mailMessage.Attachments.Add(data);//添加到附件中 } } /// <summary> /// 异步发送邮件 /// </summary> /// <param name="CompletedMethod"></param> public void SendAsync(SendCompletedEventHandler CompletedMethod) { if (mailMessage != null) { smtpClient = new SmtpClient(); smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = "smtp." + mailMessage.From.Host; smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);//注册异步发送邮件完成时的事件 smtpClient.SendAsync(mailMessage, mailMessage.Body); } } /// <summary> /// 发送邮件 /// </summary> public void Send() { if (mailMessage != null) { using (smtpClient = new SmtpClient()) { smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = "smtp." + mailMessage.From.Host; smtpClient.Send(mailMessage); mailMessage.Attachments.Dispose(); } } } } }
应该不需要拼接HTML吧,可以将table放入一个ID为mailbody的div标签中,然后获取mailbody的innerHTML就可以获取table内容和样式
@JackWang-CUMT: 能详细点吗?
@温柔的意外:
<html> <head> <title>innerHTML</title> </head> <body> <div id='mailBody'> <table> <caption>report 2005 - 2008</caption> <thead> <tr> <th> </th> <th scope="col">2005</th> <th scope="col">2006</th> <th scope="col">2007</th> <th scope="col">2008</th> </tr> </thead> <tbody> <tr> <th scope="row">a</th> <td>11,980</td> <td>12,650</td> <td>9,700</td> <td>10,600</td> </tr> <tr> <th scope="row">b</th> <td>4,780</td> <td>4,989</td> <td>6,700</td> <td>6,590</td> </tr> <tr> <th scope="row">c</th> <td>8,000</td> <td>8,100</td> <td>8,760</td> <td>8,490</td> </tr> <tr> <th scope="row">d</th> <td>3,200</td> <td>3,120</td> <td>3,700</td> <td>4,210</td> </tr> </tbody> <tfoot> <tr> <td colspan="5">2008</td> </tr> </tfoot> </table> </div> <input type='button' onclick='GetMailBody()' value='get mail body'/> </body> <script type="text/javascript"> function GetMailBody(){ var body=document.getElementById('mailBody').innerHTML; alert(body); } </script> </html>
@JackWang-CUMT: 我能看看传到邮箱的效果吗?谢谢!
@JackWang-CUMT: 感觉你的回答能解决我的问题!
@温柔的意外:
@温柔的意外: @温柔的意外: @温柔的意外: 我测试过,完全可行
@JackWang-CUMT: 那么把豆豆给你,就是这个!完美!
@温柔的意外:
string htmlbody=@" <table> <caption>report 2005 - 2008</caption> <thead> <tr> <th> </th> <th scope='col'>2005</th> <th scope='col'>2006</th> <th scope='col'>2007</th> <th scope='col'>2008</th> </tr> </thead> <tbody> <tr> <th scope='row'>a</th> <td>11,980</td> <td>12,650</td> <td>9,700</td> <td>10,600</td> </tr> <tr> <th scope='row'>b</th> <td>4,780</td> <td>4,989</td> <td>6,700</td> <td>6,590</td> </tr> <tr> <th scope='row'>c</th> <td>8,000</td> <td>8,100</td> <td>8,760</td> <td>8,490</td> </tr> <tr> <th scope='row'>d</th> <td>3,200</td> <td>3,120</td> <td>3,700</td> <td>4,210</td> </tr> </tbody> <tfoot> <tr> <td colspan='5'>2008</td> </tr> </tfoot> </table> "; SendMailHelper.SendMail sd = new SendMailHelper.SendMail(new string[] { "收件人邮箱" }, "发件人邮箱",htmlbody, "test", "发件人密码"); sd.Send();
@温柔的意外: @温柔的意外: @温柔的意外: @温柔的意外: 我测试过,完全可行
@JackWang-CUMT: 2685683534qq.com 你能把案例给我看看吗?新手学习!
@温柔的意外: 可以,你会ajax么,如果要完整实现,打通前后台,需要用JS访问后台发邮件服务?
@JackWang-CUMT: 会一点。就把你做的这个小案例发给看看就行了!
@JackWang-CUMT: SendMailHelper.SendMail sd = new SendMailHelper.SendMail(new string[] { "收件人邮箱" }, "发件人邮箱",htmlbody, "test", "发件人密码"); sd.Send();这个方法是写在后台还是前台??
@温柔的意外: 后台,你稍等一下,我写个完整的Demo,然后发给你
@温柔的意外: 已发送,请查收@温柔的意外: 后台,你稍等一下,我写个完整的Demo,然后发给你
/// <summary> /// Email助手 /// </summary> public class EmailHelper { #region 发送邮件 /// <summary> /// 发送邮件,无符件,使用HTML编码 /// </summary> /// <param name="to">接收邮件用户列表,以分号连接</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <returns>是否发送成功</returns> public static bool SendMail(string to, string subject, string body) { return SendMail(to, subject, body, string.Empty, true); } /// <summary> /// 发送邮件,有符件,使用HTML编码 /// </summary> /// <param name="to">接收邮件用户列表,以分号连接</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <param name="attach">符件路径 如:C:\\附件.rar</param> /// <returns>是否发送成功</returns> public static bool SendMail(string to, string subject, string body, string attach) { return SendMail(to, subject, body, attach, true); } /// <summary> /// 使用System.Net.Mail的发送邮件. /// </summary> /// <param name="to">接收邮件用户列表,以分号连接</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <param name="attach">符件</param> /// <param name="useHtmlFormat">是否为HTML编码发送</param> /// <returns>是否发送成功</returns> private static bool SendMail(string to, string subject, string body, string attach, bool useHtmlFormat) { string from = ConfigHelper.GetAppSettings("FromAddress"); //邮件发送者的名称 string FromName = ConfigHelper.GetAppSettings("FromName"); string sendEmailPassword = ConfigHelper.GetAppSettings("FromPwd").Decrypt(); MailMessage mailMsg = new MailMessage(); string[] mails = to.Split(';'); foreach (string mail in mails) { if (!String.IsNullOrEmpty(mail)) { mailMsg.To.Add(mail); } } mailMsg.SubjectEncoding = Encoding.Default; mailMsg.BodyEncoding = Encoding.Default; mailMsg.From = new MailAddress(from, FromName); mailMsg.Subject = subject; mailMsg.Body = body; if (attach != null && attach != "") { char[] delim = new char[] { ',' }; foreach (string sSubstr in attach.Split(delim)) { //Attachment("C:\\附件.rar"); //System.Net.Mail.Attachment MyAttachment = new System.Net.Mail.Attachment(sSubstr); //mailMsg.Attachments.Add(MyAttachment); Attachment attachment = new Attachment(sSubstr, "text/plain"); mailMsg.Attachments.Add(attachment); } } if (useHtmlFormat) mailMsg.IsBodyHtml = true; else mailMsg.IsBodyHtml = false; SmtpClient client = new SmtpClient(); //mail.163.com client.Host = ConfigHelper.GetAppSettings("FromSmtp"); //端口通常是25 client.Port = Convert.ToInt32(ConfigHelper.GetAppSettings("FromSmtpProt")); client.UseDefaultCredentials = false; //不需要做超时设置,否则经常发不了邮件,net有自已的超时机制.不设只随时都能发送成功的 //client.Timeout = 60; #region Email client.Credentials = new System.Net.NetworkCredential(from, sendEmailPassword); #endregion client.DeliveryMethod = SmtpDeliveryMethod.Network; try { client.Send(mailMsg); return true; } catch (Exception ex) { Exception source = ex; while (source.InnerException != null) source = source.InnerException; //XTrace.WriteLog("邮件发送失败!邮件标题:" + subject + "。错误消息:" + source.Message); return false; } } /// <summary> /// 使用System.Net.Mail的发送邮件. /// </summary> /// <param name="to">接收邮件用户列表,以分号连接</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <param name="attach">符件</param> /// <param name="useHtmlFormat">是否为HTML编码发送</param> /// <param name="from">发送者邮件地址</param> /// <param name="fromName">发送者称谓</param> /// <param name="sendEmailPassword">发送者邮件密码</param> /// <param name="fromSmtp">邮件服务器Smtp地址,不加http://</param> /// <param name="fromSmtpProt">邮件服务器Smtp端口</param> /// <param name="timeOut">超时时间 单位 称</param> /// <returns></returns> public static bool SendMail(string to, string subject, string body, string attach, bool useHtmlFormat, string from, string fromName, string sendEmailPassword, string fromSmtp, int fromSmtpProt) { MailMessage mailMsg = new MailMessage(); string[] mails = to.Split(';'); foreach (string mail in mails) { if (!String.IsNullOrEmpty(mail)) { mailMsg.To.Add(mail); } } mailMsg.SubjectEncoding = Encoding.Default; mailMsg.BodyEncoding = Encoding.Default; mailMsg.From = new MailAddress(from, fromName); mailMsg.Subject = subject; mailMsg.Body = body; if (attach != null && attach != "") { char[] delim = new char[] { ',' }; foreach (string sSubstr in attach.Split(delim)) { //Attachment("C:\\附件.rar"); System.Net.Mail.Attachment MyAttachment = new System.Net.Mail.Attachment(sSubstr); mailMsg.Attachments.Add(MyAttachment); } } if (useHtmlFormat) mailMsg.IsBodyHtml = true; else mailMsg.IsBodyHtml = false; SmtpClient client = new SmtpClient(); //mail.163.com client.Host = fromSmtp; //端口通常是25 client.Port = fromSmtpProt; client.UseDefaultCredentials = false; //client.Timeout = timeOut; #region Email client.Credentials = new System.Net.NetworkCredential(from, sendEmailPassword); #endregion client.DeliveryMethod = SmtpDeliveryMethod.Network; try { client.Send(mailMsg); return true; } catch (Exception ex) { Exception source = ex; while (source.InnerException != null) source = source.InnerException; //XTrace.WriteLog("邮件发送失败!邮件标题:" + subject + "。错误消息:" + source.Message); return false; } } #endregion }
试试吧!建一个类调用就行!
主要是body里要那么写,我现在想到的就是根据前台传来的数据拼接!但太麻烦了。有简单点的方法吗?
@温柔的意外: 没有最简单的办法,只有最适合你的办法!下面的还有这么些。你何不动手试试呢?
参考:http://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/14/2212255.html
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Mail; namespace WebPrint.Framework { public static class SmtpHelper { /// <summary> /// 同步发送 /// </summary> /// <param name="info"></param> public static void SendMail(SmtpInformation info) { var msg = GetMailMessage(info); var client = new SmtpClient(); client.Host = info.Server; if (!string.IsNullOrEmpty(info.Username)) client.Credentials = new NetworkCredential(info.Username, info.Password); client.Send(msg); msg.Dispose(); } /// <summary> /// 异步发送 /// </summary> /// <param name="info"></param> public static void SendMailAsync(SmtpInformation info) { var msg = GetMailMessage(info); var client = new SmtpClient(); client.Host = info.Server; if (!string.IsNullOrEmpty(info.Username)) client.Credentials = new NetworkCredential(info.Username, info.Password); client.SendAsync(msg, msg); } /// <summary> /// 获得 MailMessage 对象 /// </summary> private static MailMessage GetMailMessage(SmtpInformation info) { var msg = new MailMessage(); info.ToAddresses .Where(addr => !addr.IsNullOrEmpty()) .Select(addr => addr.ToLower()) .Distinct() .ForEach(addr => msg.To.Add(addr)); info.CcAddresses .Where(addr => !addr.IsNullOrEmpty()) .Select(addr => addr.ToLower()) .Distinct() .ForEach(addr => msg.CC.Add(addr)); msg.From = new MailAddress(info.FromAddress, info.FromDisplayName, Encoding.UTF8);//发件人地址(可以随便写),发件人姓名,编码 msg.Subject = info.Subject; msg.SubjectEncoding = Encoding.UTF8; msg.Body = info.Body; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = true; msg.Priority = MailPriority.Normal; info.Attachments.ForEach(item => msg.Attachments.Add(item)); return msg; } //可以用NVelocity模板引擎 public static string EmailTemplate(string content, string orderSystemName) { const string template = "<html><body>" + "Thank you for your confirmation!<br/>" + "You could view the order's detail information via the link below:<br/>" + "{0}<br/><br/>" + "************************************************************************************<br/>" + "This e-mail is sent by the r-pac {1} ordering system automatically.<br/>" + "Please don't reply this e-mail directly!<br/>" + "************************************************************************************<br/>" + "</body></html>"; return string.Format(template, content, orderSystemName); } public static string EmailCancelledTemplete(string content, string orderSystemName) { const string template = "<html><body>" + "Below order is cancelled:<br/>" + "{0}<br/><br/>" + "************************************************************************************<br/>" + "This e-mail is sent by the r-pac {1} ordering system automatically.<br/>" + "Please don't reply this e-mail directly!<br/>" + "************************************************************************************<br/>" + "</body></html>"; return string.Format(template, content, orderSystemName); } public static string EmailReOrderTemplete(string content, string orderSystemName) { const string template = "<html><body>" + "Below order is re_order:<br/>" + "{0}<br/><br/>" + "************************************************************************************<br/>" + "This e-mail is sent by the r-pac {1} ordering system automatically.<br/>" + "Please don't reply this e-mail directly!<br/>" + "************************************************************************************<br/>" + "</body></html>"; return string.Format(template, content, orderSystemName); } } public class SmtpInformation { public SmtpInformation() { ToAddresses = new List<string>(); CcAddresses = new List<string>(); Attachments = new Attachments(); } /// <summary> /// 发送邮件服务器地址 /// </summary> public string Server { get; set; } /// <summary> /// 登陆用户名 /// </summary> public string Username { get; set; } /// <summary> /// 登陆密码 /// </summary> public string Password { get; set; } /// <summary> /// 显示发件人email /// </summary> public string FromAddress { get; set; } /// <summary> /// 用于显示的发件人名 /// </summary> public string FromDisplayName { get; set; } /// <summary> /// 收件人列表 /// </summary> public List<string> ToAddresses { get; private set; } //抄送人列表 public List<string> CcAddresses { get; private set; } /// <summary> /// 主题 /// </summary> public string Subject { get; set; } /// <summary> /// 邮件内容 HTML格式 /// </summary> public string Body { get; set; } /// <summary> /// 附件 /// </summary> public Attachments Attachments { get; private set; } } public class Attachments : IEnumerable<Attachment> { private readonly List<Attachment> attachments; internal Attachments() { attachments = new List<Attachment>(); } public void Add(string fileName) { attachments.Add(new Attachment(fileName)); } public void Add(System.IO.Stream contentStream, string name) { attachments.Add(new Attachment(contentStream, name)); } public void ForEach(Action<Attachment> action) { attachments.ForEach(action); } public void Clear() { attachments.Clear(); } #region IEnumerable<Attachment> 成员 public IEnumerator<Attachment> GetEnumerator() { return attachments.GetEnumerator(); } #endregion #region IEnumerable 成员 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } }
你这和我的有点想进,你这太复杂了。我就要1对1的发送邮件。注:发送前台页面的数据和格式。接受邮件的人看到的和页面看到的是一样的。(表格或图都行)
@温柔的意外: 你直接把html发过去不就行了
@稳稳的河: 你是说发送网址?要的结果是收件人要看到数据就想页面一样的效果(比如:页面是表格,那么他看到的也是表格)
@温柔的意外: 不是网站,你可以把页面COPY出来(js直接有copy的方法),作为body发送,你看我上面的template其实都是拼接html
@温柔的意外: 我给个例子你把,把一个div克隆下来,那些不要你就remove(你把整个页面克隆出来)
var html = $('.inner_main_div').clone(); html.find('select[name="formatId"]').after($('#order_form select[name="formatId"] option:selected').text()).remove(); html.find('input[name="PoNo"]').after($('#order_form input[name="PoNo"]').val()).remove(); html.find('input[name="VendorPo"]').after($('#order_form input[name="VendorPo"]').val()).remove(); html.find('select[name="printShopId"]').after($('#order_form select[name="printShopId"] option:selected').text()).remove(); html.find('select[name="overage"]').after($('#order_form select[name="overage"] option:selected').text()).remove(); html.find('.title span').remove(); html.find('input:button').remove(); html.find('.addressUl').css('display', 'block'); html.find('.addressDropdown').remove(); html.find('p:first').remove(); html.find('form').attr('id', ''); html.find('.star_mark').remove(); //html.find('form span').remove(); html.find('div.address-title').remove(); html.find('div.search_action').remove(); html.find('.top_content').css({ margin: "10px 0px 0px 0px", width: "74%" }); html.find('.top_title').css("text-align", "right"); html.find('.shipto_div').css("margin-right", "50px"); html.find('input[type=text]').each(function() { if ($(this).attr('type') != 'hidden') { $(this).after($(this).val()).remove(); } });
@温柔的意外: 还有你也可以获取数据,自己拼接你想要的html,其实都是前端的东西
@稳稳的河: 我知道拼接HTML邮件,还有没有跟简单点的方法。
@温柔的意外: 上面不是说了复制,挺简单的
@稳稳的河: JackWang-CUMT写了我上面的简化版本,直接去html,你不愿意去自己试试,给个建议自己多去试试,直接要源码没什么用
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; namespace SendMail { public class SendMail { private MailMessage mailMessage; private SmtpClient smtpClient; private string password;//发件人密码 /// <summary> /// 处审核后类的实例 /// </summary> /// <param name="To">收件人地址</param> /// <param name="From">发件人地址</param> /// <param name="Body">邮件正文</param> /// <param name="Title">邮件的主题</param> /// <param name="Password">发件人密码</param> public SendMail(string[] To, string From, string Body, string Title, string Password) { mailMessage = new MailMessage(); foreach (var item in To) { mailMessage.To.Add(item); } mailMessage.From = new System.Net.Mail.MailAddress(From); mailMessage.Subject = Title; mailMessage.Body = Body; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.Priority = System.Net.Mail.MailPriority.Normal; this.password = Password; } /// <summary> /// 添加附件 /// </summary> public void Attachments(string Path) { string[] path = Path.Split(','); Attachment data; ContentDisposition disposition; for (int i = 0; i < path.Length; i++) { data = new Attachment(path[i], MediaTypeNames.Application.Octet);//实例化附件 disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);//获取附件的创建日期 disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);//获取附件的修改日期 disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);//获取附件的读取日期 mailMessage.Attachments.Add(data);//添加到附件中 } } /// <summary> /// 异步发送邮件 /// </summary> /// <param name="CompletedMethod"></param> public void SendAsync(SendCompletedEventHandler CompletedMethod) { if (mailMessage != null) { smtpClient = new SmtpClient(); smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = "smtp." + mailMessage.From.Host; smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);//注册异步发送邮件完成时的事件 smtpClient.SendAsync(mailMessage, mailMessage.Body); } } /// <summary> /// 发送邮件 /// </summary> public void Send() { if (mailMessage != null) { using (smtpClient = new SmtpClient()) { smtpClient.Timeout = 9999999; smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发件人身份的票据 smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Host = "smtp." + mailMessage.From.Host; smtpClient.Send(mailMessage); mailMessage.Attachments.Dispose(); } } } } }
不是附件,是前台页面的数据。但发送时格式也要。