C# MailKit邮件发送,HTML模板

1 篇文章 0 订阅


前言

工作笔记:VS 2019 MailKit 发送邮件,
NuGet下载:MailKit,Mimekit
引用:
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;


一、后端代码

		public string sendMail(SendMailConfig config, SendMailEntity entity)
		{
		     string receiver = entity.Receiver;
		     if (null == receiver || receiver.Trim().Equals(""))
		     {
		         throw new Exception("收件人不能为空");
		     }
		     string[] cc = (null == entity.CopyFor || entity.CopyFor.Equals("")) ? null : entity.CopyFor.Split(';');
		     string[] attach = (null == entity.Attach || entity.Attach.Equals("")) ? null : entity.Attach.Split(',');
		
		     sendMail(config.username, config.password, config.from, receiver.Split(';'), cc, null, entity.Title, entity.Content, attach, config);
		
		     return "ok";
		}

		/// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="from">发件邮箱</param>
        /// <param name="to">收件邮箱</param>
        /// <param name="cc">抄送</param>
        /// <param name="bcc">密送</param>
        /// <param name="subject">标题</param>
        /// <param name="content">内容</param>
        /// <param name="attachfilenames">附件</param>
        /// <param name="config">配置</param>
        public void sendMail(string username, string password, string from, string[] to, string[] cc, string[] bcc, string subject, string content, string[] attachfilenames, SendMailConfig config)
        {
            using (var client = new SmtpClient())
            {
                var message = new MimeMessage();
                var multipart = new Multipart("mixed");

                #region from to cc bcc
                if (string.IsNullOrWhiteSpace(from))
                {
                    message.From.Add(new MailboxAddress(from, from));
                }
                else
                {
                    message.From.Add(new MailboxAddress(config.fromdisplayname, config.from));
                }
                for (int i = 0; i < to.Length; i++)
                {
                    if (!string.ReferenceEquals(to[i], null) && !to[i].Trim().Equals(""))
                    {
                        message.To.Add(new MailboxAddress(to[i], to[i]));
                    }
                }
                if (cc != null && !cc.Equals(""))
                {
                    for (int i = 0; i < cc.Length; i++)
                    {
                        if (!string.ReferenceEquals(cc[i], null) && !cc[i].Trim().Equals(""))
                        {
                            message.Cc.Add(new MailboxAddress(cc[i], cc[i]));
                        }
                    }
                }
                if (bcc != null)
                {
                    for (int i = 0; i < bcc.Length; i++)
                    {
                        if (!string.ReferenceEquals(bcc[i], null) && !bcc[i].Trim().Equals(""))
                        {
                            message.Bcc.Add(new MailboxAddress(bcc[i], bcc[i]));
                        }
                    }
                }



                #endregion

                message.Subject = subject;

                //内容
                if (!string.IsNullOrEmpty(content))
                {
                    var Html = new TextPart(TextFormat.Html)
                    {
                        Text = content
                    };
                    multipart.Add(Html);

                }
                //附件
                if (attachfilenames != null && attachfilenames.Length > 0)
                {
                    var storage = GetStorageService();
                    for (int i = 0; i < attachfilenames.Length; i++)
                    {
                        if (!string.ReferenceEquals(attachfilenames[i], null))
                        {
                            //@分隔显示名称和唯一名称
                            string[] n = attachfilenames[i].Split('@');
                            if (n.Length >= 2)
                            {
                                var file = storage.DownLoadFile(n[1], null);

                                var attimg = new MimePart()
                                {
                                    Content = new MimeContent(file),
                                    ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                                    ContentTransferEncoding = ContentEncoding.Base64,
                                    FileName = n[0]
                                };
                                multipart.Add(attimg);
                            }
                        }
                    }
                }

                message.Body = multipart;
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                if (config.smtp.starttlsEnable && !config.smtp.sslEnable) //config.getSmtp.sslEnable 端口不再是默认端口 25 而是465
                {
                    client.Connect(config.smtp.host, config.smtp.port, SecureSocketOptions.StartTls);
                }
                else
                {
                    client.Connect(config.smtp.host, config.smtp.port, config.smtp.sslEnable);
                }


                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                // Note: only needed if the SMTP server requires authentication
                //password = System.Text.RegularExpressions.Regex.Escape(password);
                client.Authenticate(username, password);
                client.Send(message);
                client.Disconnect(true);
            }
        }
        
        /// <summary>
        /// 获取HTML模板 我的模板是配置在目录下的,通过路径拿到文件内的内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
		public string BuildByFile(string filePath)
        {
            StreamReader reader = null;
            string template = string.Empty;
            reader = new StreamReader(filePath);
            template = reader.ReadToEnd();
            reader.Close();
            return template;
        }

二、HTML模板

	<div>
    <includetail>
        <style>
            /* CLIENT-SPECIFIC STYLES */
            body, table, td, a {
                -webkit-text-size-adjust: 100%;
                -ms-text-size-adjust: 100%;
            }

            table, td {
                mso-table-lspace: 0pt;
                mso-table-rspace: 0pt;
            }

            img {
                -ms-interpolation-mode: bicubic;
            }

            .hidden {
                display: none !important;
                visibility: hidden !important;
            }

            /* iOS BLUE LINKS */
            a[x-apple-data-detectors] {
                color: inherit !important;
                text-decoration: none !important;
                font-size: inherit !important;
                font-family: inherit !important;
                font-weight: inherit !important;
                line-height: inherit !important;
            }

            /* ANDROID MARGIN HACK */
            body {
                margin: 0 !important;
            }

            div[style*="margin: 16px 0"] {
                margin: 0 !important;
            }

            @media only screen and (max-width: 639px) {
                body, #body {
                    min-width: 320px !important;
                }

                table.wrapper {
                    width: 100% !important;
                    min-width: 320px !important;
                }
            }
        </style>
        <style>
            body {
                -webkit-text-size-adjust: 100%;
                -ms-text-size-adjust: 100%;
            }

            img {
                -ms-interpolation-mode: bicubic;
            }

            body {
                margin: 0 !important;
            }
        </style>


        <table border="0" cellpadding="0" cellspacing="0" id="body"
               style="text-align: center; min-width: 640px; width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; margin: 0; padding: 0;"
               bgcolor="#fafafa">
            <tbody>
            <!-- {{--  最上边紫色的分割线 --}} -->
            <tr class="line">
                <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; height: 4px; font-size: 4px; line-height: 4px; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt;"
                    bgcolor="#6b4fbb">&nbsp;
                </td>
            </tr>
            <!-- {{--  页头的LOGO    --}} -->
            <tr class="header">
                <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; font-size: 13px; line-height: 1.6; color: #5c5c5c; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 25px 0;">
                    <!-- <img src="http://192.168.10.105/assets/mailers/gitlab_header_logo-153749eaa7ea6fafcb995161abd3247bc4c4500f31498b0c4024f50093983ac0.gif" width="55" height="50" -->
                         <!-- style="-ms-interpolation-mode: bicubic;"> -->
                </td>
            </tr>
            <tr>
                <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
                    <table border="0" cellpadding="0" cellspacing="0" class="wrapper"
                           style="width: 640px; border-collapse: separate; border-spacing: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; margin: 0 auto;">
                        <tbody>
                        <tr>
                            <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; border-radius: 3px; overflow: hidden; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 18px 25px; border: 1px solid #ededed;"
                                align="left" bgcolor="#ffffff">
                                <table border="0" cellpadding="0" cellspacing="0" class="content"
                                       style="width: 100%; border-collapse: separate; border-spacing: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
                                    <tbody>
                                    <tr>
                                        <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; color: #333333; font-size: 15px; font-weight: 400; line-height: 1.4; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 15px 5px;"
                                            align="center">
                                            <h1 style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; color: #333333; font-size: 18px; font-weight: 400; line-height: 1.4; margin: 0; padding: 0;"
                                                align="center">
                                                HI:
                                            </h1>
                                            <p>
                                                请复制下方链接至浏览器打开:
                                            </p>
                                            <p>
                                                <a href="" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%;">https://www.baidu.com/</a>
                                            </p>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr class="footer">
                <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; font-size: 13px; line-height: 1.6; color: #5c5c5c; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 25px 0;">
                    <!-- <img height="33" src="http://192.168.10.105/assets/mailers/gitlab_footer_logo-078860f148cc9596195e6bb3fa7db31c30538355576c5c3b569c414902e3d095.gif" -->
                         <!-- style="display: block; -ms-interpolation-mode: bicubic; margin: 0 auto 1em;" width="90"> -->

                    <div>
                        邮件来自XXX,不需要回复。
                    </div>
                </td>
            </tr>

            </tbody>
        </table>
    </includetail>
</div>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值