zoukankan      html  css  js  c++  java
  • 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit

    好东西一定要试一下,何况是开源,下面是代码可实现SMTP邮件发送:

    using MailKit.Net.Smtp;
    using MailKit.Security;
    using MimeKit;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        public class MailHelper
        {
            public static void Send(string email, string subject, string message)
            {
                var emailMessage = new MimeMessage();
                emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@hantianwei.cn"));
                emailMessage.To.Add(new MailboxAddress("mail", email));
                emailMessage.Subject = subject;
                emailMessage.Body = new TextPart("plain") { Text = message };
    
                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.hantianwei.cn", 465, true);
                    client.Authenticate("mail@hantianwei.cn", "******");
    
                    client.Send(emailMessage);
                    client.Disconnect(true);
    
                }
            }
    
            public static async Task SendEmailAsync(string email, string subject, string message)
            {
                var emailMessage = new MimeMessage();
    
                emailMessage.From.Add(new MailboxAddress("tianwei blogs", "mail@hantianwei.cn"));
                emailMessage.To.Add(new MailboxAddress("mail", email));
                emailMessage.Subject = subject;
                emailMessage.Body = new TextPart("plain") { Text = message };
    
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync("smtp.hantianwei.cn", 25, SecureSocketOptions.None).ConfigureAwait(false);
                    await client.AuthenticateAsync("mail@hantianwei.cn", "******");
                    await client.SendAsync(emailMessage).ConfigureAwait(false);
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                    
                }
            }
    
        }
    }

    以上代码同步异步都没有问题

    注:一般邮箱如腾讯企业邮、163等都可以发送成功,但阿里云邮件推送失败,如果有高手可实现阿里云推送邮件请告诉我一下,非常感谢!

  • 相关阅读:
    yolo_to_onnx ValueError: need more tan 1 value to unpack
    yolo_to_onnx killed
    C++ 实现二维矩阵的加减乘等运算
    Leetcode 1013. Partition Array Into Three Parts With Equal Sum
    Leetcode 1014. Best Sightseeing Pair
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 219. Contains Duplicate II
    Leetcode 890. Find and Replace Pattern
    Leetcode 965. Univalued Binary Tree
    Leetcode 700. Search in a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/hantianwei/p/5654844.html
Copyright © 2011-2022 走看看