邮件发送

南笙酒味 提交于 2020-04-07 18:30:18

 

效果

 

查看收件人的smtp通讯协议

 

code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.IO;

namespace EmailSendConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.Title = "邮件发送  http://www.cnblogs.com/suntanyong88/";
            System.Console.WriteLine("请输入参数选择您要操作状态。");
            System.Console.WriteLine("输入1 单发邮件");
            System.Console.WriteLine("输入2 群发邮件");
            System.Console.WriteLine("输入3 群发邮件并附件文件");

            string ctype = System.Console.ReadLine();
            if (ctype == "1")
            {
                //用 MailAddress 发送方法1
                CreateCopyMessage("smtp.exmail.qq.com");
            }
            if (ctype == "2")
            {
                EmailParameterSet model = new EmailParameterSet();
                model.SendEmail = "你发件人的邮箱";
                model.ConsigneeHand = "双11";
                model.SendPwd = "你的密码";//密码
                model.SendSetSmtp = "smtp.exmail.qq.com";//发送的SMTP服务地址 ,每个邮箱的是不一样的。。根据发件人的邮箱来定 (smtp.exmail.qq.com)
                model.ConsigneeAddress = "xxx@qq.com";
                model.ConsigneeName = "收件人邮箱";
                model.ConsigneeTheme = "收件人的主题";
                model.RecipientsList = "xxx@qq.com,张三,xxx测试;xxx@outlook.com,李四,xxx测试";
                model.CC = "xxx@163.com;xxx@163.com";

                #region 拼接正文
                string mailContent = FiletoRead();
                string mailBody = GenerateMailBody();
                mailContent = mailContent.Replace("{%No1%}", "xxxx");
                mailContent = mailContent.Replace("{%No2%}", "创兴");
                mailContent = mailContent.Replace("{%No3%}", "微软");
                mailContent = mailContent.Replace("{%Month%}", System.DateTime.Now.Month.ToString());
                mailContent = mailContent.Replace("{%mailBody%}", mailBody);
                mailContent = mailContent.Replace("{%url1%}", "http://www.taobao.com");
                mailContent = mailContent.Replace("{%url2%}", "http://www.jingdong.com");
                mailContent = mailContent.Replace("{%time%}", System.DateTime.Now.ToShortDateString());
                #endregion
                model.SendContent = mailContent;

                if (MailSend(model, true))
                {
                    Console.WriteLine("邮件发送成功!");
                }
                else
                {
                    Console.WriteLine("邮件发送失败!");
                }
            }
            if (ctype == "3")
            {

                EmailParameterSet model = new EmailParameterSet();
                model.SendEmail = "你发件人的邮箱";
                model.ConsigneeHand = "双11";
                model.SendPwd = "你的密码";//密码
                model.SendSetSmtp = "smtp.exmail.qq.com";//发送的SMTP服务地址 ,每个邮箱的是不一样的。。根据发件人的邮箱来定 (smtp.exmail.qq.com)
                model.ConsigneeAddress = "xxx@qq.com";
                model.ConsigneeName = "收件人邮箱";
                model.ConsigneeTheme = "收件人的主题";
                model.RecipientsList = "xxx@qq.com,张三,xxx测试;xxx@outlook.com,李四,xxx测试";
                model.CC = "xxx@163.com;xxx@163.com";

                #region 拼接正文
                string mailContent = FiletoRead();
                string mailBody = GenerateMailBody();
                mailContent = mailContent.Replace("{%No1%}", "xxxx");
                mailContent = mailContent.Replace("{%No2%}", "创兴");
                mailContent = mailContent.Replace("{%No3%}", "微软");
                mailContent = mailContent.Replace("{%Month%}", System.DateTime.Now.Month.ToString());
                mailContent = mailContent.Replace("{%mailBody%}", mailBody);
                mailContent = mailContent.Replace("{%url1%}", "http://www.taobao.com");
                mailContent = mailContent.Replace("{%url2%}", "http://www.jingdong.com");
                mailContent = mailContent.Replace("{%time%}", System.DateTime.Now.ToShortDateString());
                #endregion
                model.SendContent = mailContent;

                if (MailSend2(model, true))
                {
                    Console.WriteLine("邮件发送成功!");
                }
                else
                {
                    Console.WriteLine("邮件发送失败!");
                }
            }


            //用 SmtpClient 发送方法2

            Console.ReadLine();
        }


        #region 方法1

        public static void CreateCopyMessage(string server)
        {
            MailAddress from = new MailAddress("xxxx@seagull2.cn", "姓名");
            MailAddress to = new MailAddress("xxx@qq.com", "Jane Clayton");
            MailMessage message = new MailMessage(from, to);
            // message.Subject = "Using the SmtpClient class.";
            message.Subject = "Using the SmtpClient class.";
            message.Body = @"Using this feature, you can send an e-mail message from an application very easily.";
            // Add a carbon copy recipient.
            MailAddress copy = new MailAddress("xxxx@163.com");
            message.CC.Add(copy);
            SmtpClient client = new SmtpClient(server);
            // Include credentials if the server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            Console.WriteLine("Sending an e-mail message to {0} by using the SMTP host {1}.",
                 to.Address, client.Host);


            //添加附件  
            Attachment a = new Attachment(@"E:/读卡器.rar");
            message.Attachments.Add(a);  

            //用户登录信息
            NetworkCredential myCredential = new NetworkCredential("邮件地址", "密码");
            client.Credentials = myCredential;//登录

            //设置超时时间  
            client.Timeout = 9999; 

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateCopyMessage(): {0}",
                            ex.ToString());
            }
          
        }
        #endregion

        #region 方法2
        /// <summary>
        /// 发送email
        /// </summary>
        /// <param name="EPSModel">实体</param>
        /// <param name="isbodyhtml">是否发送html格式</param>
        /// <returns></returns>
        public static bool MailSend(EmailParameterSet EPSModel, bool isbodyhtml)
        {
            try
            {
                if (EPSModel == null) return false;
                //确定smtp服务器端的地址,实列化一个客户端smtp 
                System.Net.Mail.SmtpClient sendSmtpClient = new System.Net.Mail.SmtpClient(EPSModel.SendSetSmtp);//发件人的邮件服务器地址
                //构造一个发件的人的地址
                System.Net.Mail.MailAddress sendMailAddress = new MailAddress(EPSModel.SendEmail, EPSModel.ConsigneeTheme, Encoding.UTF8);//发件人的邮件地址和收件人的标题、编码


                //构造一个收件的人的地址
                System.Net.Mail.MailAddress consigneeMailAddress = new MailAddress(EPSModel.ConsigneeAddress, EPSModel.ConsigneeName, Encoding.UTF8);//收件人的邮件地址和收件人的名称 和编码

                //构造一个Email对象
                System.Net.Mail.MailMessage mailMessage = new MailMessage(sendMailAddress, consigneeMailAddress);//发件地址和收件地址
                mailMessage.Subject = EPSModel.ConsigneeTheme;//邮件的主题
                mailMessage.BodyEncoding = Encoding.UTF8;//编码
                mailMessage.SubjectEncoding = Encoding.UTF8;//编码
                mailMessage.Body = EPSModel.SendContent;//发件内容
                mailMessage.IsBodyHtml = isbodyhtml;//获取或者设置指定邮件正文是否为html

                //设置邮件信息 (指定如何处理待发的电子邮件)
                sendSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定如何发邮件 是以网络来发
                sendSmtpClient.EnableSsl = false;//服务器支持安全接连,安全则为true

                sendSmtpClient.UseDefaultCredentials = false;//是否随着请求一起发

                if (!string.IsNullOrEmpty(EPSModel.RecipientsList))
                {//收件人集合
                    string[] emailList = EPSModel.RecipientsList.TrimEnd(';').Split(';');
                    foreach (string item in emailList)
                    {
                        string[] s = item.Split(',');
                        MailAddress copy = new MailAddress(s[0], s[1], Encoding.UTF8);
                        mailMessage.To.Add(copy);
                    }
                }
                if (!string.IsNullOrEmpty(EPSModel.CC))
                {//抄送人集合
                    string[] sList = EPSModel.CC.TrimEnd(';').Split(';');
                    foreach (string t in sList)
                    {
                        MailAddress copy = new MailAddress(t);
                        mailMessage.CC.Add(copy);

                    }
                }
                //用户登录信息
                NetworkCredential myCredential = new NetworkCredential(EPSModel.SendEmail, EPSModel.SendPwd);
                sendSmtpClient.Credentials = myCredential;//登录
                sendSmtpClient.Send(mailMessage);//发邮件
                return true;//发送成功


            }
            catch (Exception)
            {
                return false;//发送失败
            }
        }
        #endregion 


        #region 方法3
        /// <summary>
        /// 发送email(带附件)
        /// </summary>
        /// <param name="EPSModel">实体</param>
        /// <param name="isbodyhtml">是否发送html格式</param>
        /// <returns></returns>
        public static bool MailSend2(EmailParameterSet EPSModel, bool isbodyhtml)
        {
            try
            {
                if (EPSModel == null) return false;
                //确定smtp服务器端的地址,实列化一个客户端smtp 
                System.Net.Mail.SmtpClient sendSmtpClient = new System.Net.Mail.SmtpClient(EPSModel.SendSetSmtp);//发件人的邮件服务器地址
                //构造一个发件的人的地址
                System.Net.Mail.MailAddress sendMailAddress = new MailAddress(EPSModel.SendEmail, EPSModel.ConsigneeTheme, Encoding.UTF8);//发件人的邮件地址和收件人的标题、编码


                //构造一个收件的人的地址
                System.Net.Mail.MailAddress consigneeMailAddress = new MailAddress(EPSModel.ConsigneeAddress, EPSModel.ConsigneeName, Encoding.UTF8);//收件人的邮件地址和收件人的名称 和编码

                //构造一个Email对象
                System.Net.Mail.MailMessage mailMessage = new MailMessage(sendMailAddress, consigneeMailAddress);//发件地址和收件地址
                mailMessage.Subject = EPSModel.ConsigneeTheme;//邮件的主题
                mailMessage.BodyEncoding = Encoding.UTF8;//编码
                mailMessage.SubjectEncoding = Encoding.UTF8;//编码
                mailMessage.Body = EPSModel.SendContent;//发件内容
                mailMessage.IsBodyHtml = isbodyhtml;//获取或者设置指定邮件正文是否为html

                //设置邮件信息 (指定如何处理待发的电子邮件)
                sendSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定如何发邮件 是以网络来发
                sendSmtpClient.EnableSsl = false;//服务器支持安全接连,安全则为true

                sendSmtpClient.UseDefaultCredentials = false;//是否随着请求一起发

                //添加附件  
                Attachment a = new Attachment(@"E:/读卡器.rar");
                mailMessage.Attachments.Add(a); 

                if (!string.IsNullOrEmpty(EPSModel.RecipientsList))
                {//收件人集合
                    string[] emailList = EPSModel.RecipientsList.TrimEnd(';').Split(';');
                    foreach (string item in emailList)
                    {
                        string[] s = item.Split(',');
                        MailAddress copy = new MailAddress(s[0], s[1], Encoding.UTF8);
 
                        mailMessage.To.Add(copy);
                    }
                }
                if (!string.IsNullOrEmpty(EPSModel.CC))
                {//抄送人集合
                    string[] sList = EPSModel.CC.TrimEnd(';').Split(';');
                    foreach (string t in sList)
                    {
                        MailAddress copy = new MailAddress(t);
                        mailMessage.CC.Add(copy);

                    }
                }
                //用户登录信息
                NetworkCredential myCredential = new NetworkCredential(EPSModel.SendEmail, EPSModel.SendPwd);
                sendSmtpClient.Credentials = myCredential;//登录
                sendSmtpClient.Send(mailMessage);//发邮件
                return true;//发送成功


            }
            catch (Exception)
            {
                return false;//发送失败
            }
        }
        #endregion 

        /// <summary>
        /// 异步发送
        /// </summary>
        //public static void createCopyMessgage2(string server)
        //{
        //    // Command line argument must the the SMTP host.
        //    SmtpClient client = new SmtpClient(server);
        //    // Specify the e-mail sender.
        //    // Create a mailing address that includes a UTF8 character
        //    // in the display name.
        //    MailAddress from = new MailAddress("jane@contoso.com",
        //       "Jane " + (char)0xD8 + " Clayton",
        //    System.Text.Encoding.UTF8);
        //    // Set destinations for the e-mail message.
        //    MailAddress to = new MailAddress("ben@contoso.com");
        //    // Specify the message content.
        //    MailMessage message = new MailMessage(from, to);
        //    message.Body = "This is a test e-mail message sent by an application. ";
        //    // Include some non-ASCII characters in body and subject.
        //    string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
        //    message.Body += Environment.NewLine + someArrows;
        //    message.BodyEncoding = System.Text.Encoding.UTF8;
        //    message.Subject = "test message 1" + someArrows;
        //    message.SubjectEncoding = System.Text.Encoding.UTF8;
        //    // Set the method that is called back when the send operation ends.
        //    client.SendCompleted += new
        //    SendCompletedEventHandler(SendCompletedCallback);
        //    // The userState can be any object that allows your callback 
        //    // method to identify this send operation.
        //    // For this example, the userToken is a string constant.
        //    string userState = "test message1";
        //    client.SendAsync(message, userState);
        //    Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
        //    string answer = Console.ReadLine();
        //    // If the user canceled the send, and mail hasn't been sent yet,
        //    // then cancel the pending operation.
        //    if (answer.StartsWith("c") && mailSent == false)
        //    {
        //        client.SendAsyncCancel();
        //    }
        //    // Clean up.
        //    message.Dispose();
        //    Console.WriteLine("Goodbye.");
        //}


        #region 辅助方法
        /// <summary>
        /// 文件读取
        /// </summary>
        private static string FiletoRead()
        {
            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("Resources/emailTemplate.htm"))
                {
                    return  sr.ReadToEnd();
                }
            }
            catch (Exception e)
            {
               
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
                return "";
            }
        }


        public static string GenerateMailBody()
        {
            StringBuilder mailBody = new StringBuilder();

            for (int i = 0; i < 5; i++)
            {
                StringBuilder mailRow = new StringBuilder();
                mailRow.AppendLine(CreateHtmlCell("关键工序"));
                mailRow.AppendLine(CreateHtmlCell("验收范围"));
                mailRow.AppendLine(CreateHtmlCell("验收部位"));
                mailRow.AppendLine(CreateHtmlCell("要求整改完成日期"));
                mailRow.AppendLine(CreateHtmlCell("不合格项"));
                mailRow.AppendLine(CreateHtmlCell("不合格情况说明"));

                mailBody.AppendLine(CreateHtmlRow(mailRow.ToString()));
            }


            return mailBody.ToString();
        }



        /// <summary>
        /// 创建html表格的列
        /// </summary>
        /// <param name="cellValue">表格的列的值</param>
        /// <returns></returns>
        private static string CreateHtmlCell(string cellValue)
        {
            StringBuilder mailCell = new StringBuilder();

            mailCell.Append("<td>");
            mailCell.Append(cellValue);
            mailCell.Append("</td>");

            return mailCell.ToString();
        }

        /// <summary>
        /// 创建html表格的行
        /// </summary>
        /// <param name="rowData">表格的行的值</param>
        /// <returns></returns>
        private static string CreateHtmlRow(string rowData)
        {
            StringBuilder mailRow = new StringBuilder();

            mailRow.Append("<tr>");
            mailRow.Append(rowData);
            mailRow.Append("</tr>");

            return mailRow.ToString();
        }
        #endregion
    }
}

 

源代码下载

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!