netcore 简单实现邮件发送

在很多应用系统中,都会有邮件发送功能。例如当用户注册过程中向用户邮箱发送验证信息;当客户完成订单时发送邮件进行提醒;当系统出现异常时向指定账号发送邮件报警等等。

现今在实现邮件发送功能时,更多的是选择使用第三方组件Mailkit;或者是使用一些云邮箱服务,例如Amazon Simple Email Service。

微软本身封装的组件stmpclient对邮件的支持力度不够,特别是ssl方面,现在已经慢慢的淘汰了。曾经在使用阿里云作为服务器需要发邮件时,阿里云提示禁用25端口(25端口不安全,容易被黑)而推荐使用465端口。但是微软的StmpClient竟然不支持465...着实坑了一把

MailKit简单实现邮件发送

MailKit是开源的,基于MimeKit的跨平台.NET邮件库,支持IMAP、POP3、SMTP协议。也是当前微软推荐使用的。

开源地址:https://github.com/jstedfast/MailKit

以下是简单实现邮件发送功能

 1    public class MailKitManagement:IEmail
 2     {
 3         public readonly MailKitConfig _mailKitConfig;
 4         public MailKitManagement(IOptions<MailKitConfig> mailKitConfigOption)
 5         {
 6             _mailKitConfig = mailKitConfigOption?.Value;
 7         }
 8         /// <summary>
 9         ///
10         /// </summary>
11         /// <param name="toMailAddressList"></param>
12         /// <param name="subject"></param>
13         /// <param name="body"></param>
14         /// <param name="isHtml"></param>
15         /// <returns></returns>
16         public async Task SendMessageAsync(List<string> toMailAddressList,List<string> ccAddresList ,string subject, string body, bool isHtml = false)
17         {
18             var mailMessage = new MimeMessage();
19             mailMessage.From.Add(new MailboxAddress(_mailKitConfig.DisplayName, _mailKitConfig.MailAddress));
20             foreach (var mailAddressItem in toMailAddressList)
21             {
22                 mailMessage.To.Add(MailboxAddress.Parse(mailAddressItem));
23             }
24             if (ccAddresList != null)
25             {
26                 ccAddresList.ForEach(p =>
27                 {
28                     mailMessage.Cc.Add(MailboxAddress.Parse(p));
29                 });
30             }
31
32             mailMessage.Subject = subject;
33             if (isHtml)
34             {
35                 mailMessage.Body = new TextPart(TextFormat.Html)
36                 {
37                     Text = body,
38                 };
39             }
40             else
41             {
42                 mailMessage.Body = new TextPart(TextFormat.Plain)
43                 {
44                     Text = body,
45                 };
46             }
47             using (var client = new MailKit.Net.Smtp.SmtpClient())
48             {
49                 if (_mailKitConfig.IsSsl)
50                 {
51                     client.ServerCertificateValidationCallback = (s, c, h, e) => true;
52                 }
53
54                 client.Connect(_mailKitConfig.MailServer, _mailKitConfig.SmtpPort, false);
55
56                 // Disable the XOAUTH2 authentication mechanism.  
57                 client.AuthenticationMechanisms.Remove("XOAUTH2");
58
59                 // Note: only needed if the SMTP server requires authentication  
60                 client.Authenticate(_mailKitConfig.MailAddress, _mailKitConfig.Password);
61                 await client.SendAsync(mailMessage);
62                 client.Disconnect(true);
63             }
64         }
65     }

MailKitConfig定义

1    public class MailKitConfig
2     {
3         public string MailServer { get; set; }
4         public int SmtpPort { get; set; }
5         public bool IsSsl { get; set; }
6         public string DisplayName { get; set; }
7         public string MailAddress { get; set; }
8         public string Password { get; set; }
9     }

Amazon Simple Email Service简单实现发送邮件

Amazon Simple Email Service 是Amazon提供的邮件服务。需要有响应的Amazon账号,而且在达到一定量时会被要求收费,一般不建议个人使用。对于一些企业可以考虑(但也很少会用)。(之前工作中跟老外部分有交互时,老外推荐使用....)

 1     /*
 2      * Amazon Simple Email Service
 3      * 参照 https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-net.html
 4      *
 5      */
 6     /// <summary>
 7     ///  aws email helper
 8     /// need to using AWSSDK.Core.3.7.0.44 and AWSSDK.SimpleEmail.3.7.0.42.
 9     /// </summary>
10     public class AwsEmailManagement:IEmail
11     {
12
13         private readonly AwsEmailConfig _awsConfig;
14         public AwsEmailManagement(IOptions<AwsEmailConfig> awsConfigOption)
15         {
16             this._awsConfig = awsConfigOption?.Value;
17         }
18
19         /// <summary>
20         /// send email
21         /// </summary>
22         /// <param name="toEmailList"></param>
23         /// <param name="ccEmailList"></param>
24         /// <param name="subject"></param>
25         /// <param name="body"></param>
26         /// <param name="isHtml"></param>
27         /// <returns></returns>
28         public async Task SendMessageAsync(List<string> toMailAddressList, List<string> ccAddresList, string subject, string body, bool isHtml = false)
29         {
30
31             AWSCredentials awsCredentials = new BasicAWSCredentials(_awsConfig.AccessKey, _awsConfig.SecretKey);
32             AmazonSimpleEmailServiceConfig clientConfiguration = new AmazonSimpleEmailServiceConfig();
33             if (_awsConfig.IsEnableProxy)
34             {
35                 clientConfiguration.ProxyHost = _awsConfig.ProxyUrl;
36                 clientConfiguration.ProxyPort = _awsConfig.ProxyPort;
37             }
38             using (var client = new AmazonSimpleEmailServiceClient(awsCredentials, clientConfiguration))
39             {
40                 var sendRequest = new SendEmailRequest
41                 {
42                     Source = _awsConfig.EmailAddress,
43                     Destination = new Destination
44                     {
45                         ToAddresses = toMailAddressList,
46                     },
47                     Message = new Message
48                     {
49                         Subject = new Content(subject),
50                         Body = new Body(),
51                     },
52
53                 };
54
55                 if (isHtml)
56                 {
57                     sendRequest.Message.Body.Html = new Content(body);
58                 }
59                 else
60                 {
61                     sendRequest.Message.Body.Text = new Content(body);
62                 }
63                 if (ccAddresList != null && ccAddresList.Count > 0)
64                 {
65                     sendRequest.Destination.CcAddresses = ccAddresList;
66                 }
67
68                 //   sendRequest.ConfigurationSetName = "";
69
70                 var response = await client.SendEmailAsync(sendRequest);
71             }
72         }
73     }

配置文件类(AwsEmailConfig)定义

 1     public class AwsEmailConfig
 2     {
 3         public string AccessKey { get; set; }
 4         public string SecretKey { get; set; }
 5         public bool IsEnableProxy { get; set; }
 6         public string ProxyUrl { get; set; }
 7         public int ProxyPort { get; set; }
 8
 9         public string EmailAddress { get; set; }
10
11     }

netcore 简单实现邮件发送

原文:https://www.cnblogs.com/johnyong/p/15183177.html

以上是netcore 简单实现邮件发送的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>