邮件发送已经说烂了的功能

Posted 我隻寫平民程序

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了邮件发送已经说烂了的功能相关的知识,希望对你有一定的参考价值。

       我相信每一个系统,都会有邮件发送的场景,而且这种使用场景有很多,比如登入一个系统,忘记密码,那就要通过忘记密码功能,检查你注册邮件,然后发一封重设密码的邮件给你(当然现在可能通过手机验证码处理的方案多)。

      到今天为止我一直以为,.NET发送邮件组件有很多,我之前了解的有.Net 自带的System.Net.Mail,JMail,MimeKit&MailKit。

今天我用度娘搜索了一下“发送邮件 组件”,搜索结果大概汇总一下,.Net 自带的,CDO 组件,JMail 组件 就这三个。没有搜索到 MimeKit&MailKit,

但是单独搜“MailKit”能够搜索到,而且是大牛 张善友 写的,那我暂时先说一下 MimeKit&MailKit吧。

友情推荐一下 张善友 http://www.cnblogs.com/shanyou/p/4034298.html 

MimeKit&MailKit 外国开源邮件发送组件,其实是由两个组件组成

MimeKit 负责处理寄件者,消息,附件 等等内容相关的。

MimeKit 官网:http://www.mimekit.net/

MimeKit GitHub https://github.com/jstedfast/MimeKit

开发指南:http://www.mimekit.net/docs/html/Introduction.htm

MailKit 负责发送相关的。

MailKit GitHub:https://github.com/jstedfast/MailKit

贴几段代码让大家感受一下

MimeKit 部分

var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";

message.Body = new TextPart ("plain") {
    Text = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
"
};
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
message.Subject = "How you doin?";

// create our message text, just like before (except don\'t set it as the message.Body)
var body = new TextPart ("plain") {
    Text = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
"
};

// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
    ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
    ContentTransferEncoding = ContentEncoding.Base64,
    FileName = Path.GetFileName (path)
};

// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);

// now set the multipart/mixed as the message body
message.Body = multipart;
   var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey", "joey@friends.com"));
            message.To.Add (new MailboxAddress ("Alice", "alice@wonderland.com"));
            message.Subject = "How you doin?";

            var builder = new BodyBuilder ();

            // Set the plain-text version of the message text
            builder.TextBody = @"Hey Alice,

What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.

Will you be my +1?

-- Joey
";

            // In order to reference sexy-pose.jpg from the html text, we\'ll need to add it
            // to builder.LinkedResources and then use its Content-Id value in the img src.
            var image = builder.LinkedResources.Add (@"C:\\Users\\Joey\\Documents\\Selfies\\sexy-pose.jpg");
            image.ContentId = MimeUtils.GenerateMessageId ();

            // Set the html version of the message text
            builder.HtmlBody = string.Format (@"<p>Hey Alice,<br>
<p>What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.<br>
<p>Will you be my +1?<br>
<p>-- Joey<br>
<center><img src=""cid:{0}""></center>", image.ContentId);

            // We may also want to attach a calendar event for Monica\'s party...
            builder.Attachments.Add (@"C:\\Users\\Joey\\Documents\\party.ics");

            // Now we just need to set the message body and we\'re done
            message.Body = builder.ToMessageBody ();

怎么样?是不是感觉老外写得东西,比较好看,易懂啊。

MailKit 部分

using System;

using MailKit.Net.Smtp;
using MailKit;
using MimeKit;

namespace TestClient {
    class Program
    {
        public static void Main (string[] args)
        {
            var message = new MimeMessage ();
            message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com"));
            message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com"));
            message.Subject = "How you doin\'?";

            message.Body = new TextPart ("plain") {
                Text = @"Hey Chandler,

I just wanted to let you know that Monica and I were going to go play some paintball, you in?

-- Joey"
            };

            using (var client = new SmtpClient ()) {
                client.Connect ("smtp.friends.com", 587, false);

                // 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
                client.Authenticate ("joey", "password");

                client.Send (message);
                client.Disconnect (true);
            }
        }
    }
}

这个是不是感觉跟.Net 发送邮件部分差不多啊!

下面是我封装的.Net 发送邮件部分代码,做个对比

    public class Mail
    {
        
        private static SystemMailHostConfig _config;
        public static Mail SystemMail
        {
            get { return new Mail(); }
        }

        public Mail()
        {
            _config = new SystemMailHostConfig
            {
                FromName = MailConfig.SystemMailFromName,
                From = MailConfig.SystemMailFrom,
                MailHostConfig = new MailHostConfig
                {
                    HostName = MailConfig.SmtpHostName,
                    Account = MailConfig.MailAccount,
                    Password = MailConfig.MailPassword
                }
            };
        }

        public Mail(SystemMailHostConfig config)
        {
            _config = config;
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message">默认为null。 System.Net.Mail.MailMessage </param>
        public void Send(MailContext context, MailMessage message = null)
        {
            //ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
            var sender = new SmtpClient();
            message = message ?? new MailMessage();
            if (context.Receivers.IsNotNullOrEmpty())
            {
                message.To.AddRange(context.Receivers.ToArray());
            }
            if (context.Ccs.IsNotNullOrEmpty())
            {
                message.CC.AddRange(context.Ccs.ToArray());
            }
            if (context.Bccs.IsNotNullOrEmpty())
            {
                message.Bcc.AddRange(context.Bccs.ToArray());
            }
            message.Subject = context.Subject;
            message.Body = context.Body;

            if (context.Attachments.IsNotNullOrEmpty())
            {
                message.Attachments.AddRange(context.Attachments.ToArray());
            }
            message.IsBodyHtml = true;
            try
            {
                message.From = new MailAddress(_config.From, _config.FromName);
                sender.Port = 2620;
                sender.Host = _config.MailHostConfig.HostName;
                sender.UseDefaultCredentials = false;
                sender.Credentials = new NetworkCredential(_config.MailHostConfig.Account, _config.MailHostConfig.Password);
                sender.DeliveryMethod = SmtpDeliveryMethod.Network;
                sender.EnableSsl = true;
                sender.Send(message);
            }
            catch
            {
                _config = new SystemMailHostConfig
                {
                    FromName = MailConfig.StandbySystemMailFromName,
                    From = MailConfig.StandbySystemMailFrom,
                    MailHostConfig = new MailHostConfig
                    {
                        HostName = MailConfig.StandbySmtpHostName,
                        Account = MailConfig.StandbyMailAccount,
                        Password = MailConfig.StandbyMailPassword
                    }
                };
                message.From = new MailAddress(_config.From, _config.FromName);
                sender.Port = 587;
                sender.Host = _config.MailHostConfig.HostName;               
                sender.UseDefaultCredentials = false;
                sender.Credentials = new NetworkCredential(_config.MailHostConfig.Account, _config.MailHostConfig.Password);
                sender.DeliveryMethod = SmtpDeliveryMethod.Network;
                sender.EnableSsl = true;
                sender.Send(message);
            }
        }
    }

MimeKit 和 MailKit 支持最新的国际化的电子邮件标准,是.NET 中为一个支持完整支持这些标准电子邮件库,且它还支持.NET/Mono的所有平台,包括移动电话、平板等,希望大家在架构多一种方案,多一种选择。

 

以上是关于邮件发送已经说烂了的功能的主要内容,如果未能解决你的问题,请参考以下文章

优秀软件架构师成长之路

面试准备 - 分布式系统 CAP 理论

优秀软件架构师成长之路

CountDownLatch和CyclicBarrier的区别

初识java这个小姑娘

再见!乔布斯的 iPhone X