IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发工具 -> .NET Core MailKit Email 邮件发送 -> 正文阅读

[开发工具].NET Core MailKit Email 邮件发送

什么是授权码,它又是如何设置?_QQ邮箱帮助中心

MailKit是流行且强大的.NET邮件处理框架

1、NET Core
管理 NuGet 程序包(N)...

MailKit

1、MailHelper.cs

using MimeKit;
using Config;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Talk.Extensions;

namespace CoreLibrary
{
    public static class MailHelper
    {
        public static async Task<bool> SendMail(string title, string content, MailRequest mailInfo = null)
        {
            if (mailInfo == null)
            {
                mailInfo = await FileConfig.GetMailInfoAsync();
                if (mailInfo.MailPwd.IsNullOrWhiteSpace() ||
                    mailInfo.MailFrom.IsNullOrWhiteSpace() ||
                    mailInfo.MailHost.IsNullOrWhiteSpace())
                {
                    throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
                }
            }

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(mailInfo.MailFrom, mailInfo.MailFrom));
            foreach (var mailTo in mailInfo.MailTo.Replace(";", ";").Replace(",", ";").Replace(",", ";").Split(';'))
            {
                message.To.Add(new MailboxAddress(mailTo, mailTo));
            }
            message.Subject = string.Format(title);
            message.Body = new TextPart("html")
            {
                Text = content
            };
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                await client.ConnectAsync(mailInfo.MailHost, 465, true);
                await client.AuthenticateAsync(mailInfo.MailFrom, mailInfo.MailPwd);
                await client.SendAsync(message);
                await client.DisconnectAsync(true);
            }
            return true;
        }

        public static async Task<bool> SendMail(string title, string content, string mailTo)
        {
            var info = await FileConfig.GetMailInfoAsync();
            if (info.MailPwd.IsNullOrWhiteSpace() || info.MailFrom.IsNullOrWhiteSpace() || info.MailHost.IsNullOrWhiteSpace())
                throw new Exception("请先在 [/seting] 页面配置邮箱设置。");
            info.MailTo = mailTo;
            return await SendMail(title, content, info);
        }
    }
}

2、FileConfig.cs

using Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Config
{
    public static class FileConfig
    {
        private static string filePath = "File/Mail.txt";

        private static MailRequest mailData = null;
        public static async Task<MailRequest> GetMailInfoAsync()
        {
            if (mailData == null)
            {
                if (!System.IO.File.Exists(filePath)) return new MailRequest();
                var mail = await System.IO.File.ReadAllTextAsync(filePath);
                mailData = JsonConvert.DeserializeObject<MailRequest>(mail);
            }
            //深度复制,调用方修改。
            return JsonConvert.DeserializeObject<MailRequest>(JsonConvert.SerializeObject(mailData));
        }

        public static async Task<bool> SaveMailInfoAsync(MailRequest MailRequest)
        {
            mailData = MailRequest;
            await System.IO.File.WriteAllTextAsync(filePath, JsonConvert.SerializeObject(MailRequest));
            return true;
        }
    }
}

3、MailRequest.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models
{
    public class MailRequest
    {
        /// <summary>
        /// 发件邮箱
        /// </summary>
        public string MailFrom { get; set; }
        /// <summary>
        /// 邮箱密码
        /// </summary>
        public string MailPwd { get; set; }
        /// <summary>
        /// 发件服务器
        /// </summary>
        public string MailHost { get; set; }
        /// <summary>
        /// 收件邮箱
        /// </summary>
        public string MailTo { get; set; }
    }

    public class SendMailRequest
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public MailRequest MailInfo { get; set; } = null;
    }
}

4、Constant.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Config
{
    public class Constant
    {
        public const string MailTitle = "提示";
        public const string MailContent = "MailContent";
        public const string MailFrom = "123456789@qq.com";
        public const string MailTo = "987654321@qq.com";
        public const string MailPassword = "授权码,不是QQ邮箱密码";
        public const string MailHost = "smtp.qq.com";
    }
}

5、EmailController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Config;
using CoreLibrary;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailController : ControllerBase
    {
        public EmailController()
        { }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> SendMail([FromBody] SendMailRequest model)
        {
            model.MailInfo.MailFrom = Constant.MailFrom;
            model.MailInfo.MailPwd = Constant.MailPassword;
            model.MailInfo.MailHost = Constant.MailHost;
            model.MailInfo.MailTo = Constant.MailTo;

            return await MailHelper.SendMail(model.Title, model.Content, model.MailInfo);
        }
    }
}

*
========= NET Framework =========
1、EmailHelper.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.ServiceModel;
using System.Text;

namespace CoreLibrary
{
    public class EmailHelper
    {
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="Mail_ad">收件人</param>
        /// <param name="Mail_cc">抄送人</param>
        /// <param name="title">标题</param>
        /// <param name="msg">内容</param>
        /// <param name="files">附件</param>
        public void SendEmail(List<string> Mail_ad, List<string> Mail_cc, string title, string msg, List<string> files)
        {
            string FromAddress = ConfigurationManager.AppSettings["FromAddress"];
            string Password = ConfigurationManager.AppSettings["FromPassword"];
            string Sender = ConfigurationManager.AppSettings["FromSender"];
            string SmtpHost = ConfigurationManager.AppSettings["SmtpHost"];
            string SmtpPort = ConfigurationManager.AppSettings["SmtpPort"];

            MailAddress from = new MailAddress(FromAddress, Sender);
            SmtpClient client = new SmtpClient(SmtpHost, Convert.ToInt32(SmtpPort));
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(FromAddress, Password);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = true;

            if (Mail_ad != null && Mail_ad.Count > 0)
            {
                for (int i = 0; i < Mail_ad.Count; i++)
                {
                    MailMessage message = new MailMessage();
                    message.From = from;
                    message.To.Add(Mail_ad[i].ToString());
                    if (Mail_cc != null && Mail_cc.Count > 0 && i == 0)
                    {
                        foreach (string item in Mail_cc)
                            message.CC.Add(item);
                    }
                    message.Subject = title;
                    message.Body = msg;
                    message.BodyEncoding = System.Text.Encoding.Default;
                    message.IsBodyHtml = true;
                    message.Attachments.Clear();
                    if (files != null && files.Count != 0)
                    {
                        decimal total = 0;
                        foreach (string item in files)
                        {
                            System.IO.FileInfo file = new System.IO.FileInfo(item);
                            total += file.Length / 1024;
                        }
                        if (total > 1024)
                            throw new FaultException("The file is too large.");
                        else
                        {
                            foreach (string item in files)
                            {
                                Attachment attach = new Attachment(item);
                                message.Attachments.Add(attach);
                            }
                        }
                    }
                    try
                    {
                        log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                        logger.Info("Entered SendEmail");
                        client.Send(message);
                    }
                    catch (Exception ex)
                    {
                        log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
                        logger.Error(ex.ToString());
                    }
                    finally
                    {
                        message.Dispose();
                    }
                }
            }
            else
                throw new ArgumentNullException();
        }
    }
}

2、调用

public void SendEmailByMessage()
{
    StringBuilder contents = new StringBuilder();
    string title = string.Empty;
    string address = string.Empty;
    SendMail(title, contents.ToString(), address);
}

private void SendMail(string title, string content, string address)
{
    EmailHelper eh = new EmailHelper();
    List<string> files = new List<string>();
    List<string> mail_ad = new List<string>();
    List<string> mail_cc = null;
    string cc = ConfigurationManager.AppSettings["ToCC"];
    if (!string.IsNullOrEmpty(address))
        mail_ad.Add(address);
    if (!string.IsNullOrEmpty(cc))
        mail_cc = cc.Split(new char[] { ',' }).Distinct().ToList();
    eh.SendEmail(mail_ad, mail_cc, title, content, files);
}


=========邮箱设置=========
什么是授权码,它又是如何设置?_QQ邮箱帮助中心

1、邮箱设置
*

2、邮箱设置 - 账户

3、POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

4、授权码

*
*
*
*
*

  开发工具 最新文章
Postman接口测试之Mock快速入门
ASCII码空格替换查表_最全ASCII码对照表0-2
如何使用 ssh 建立 socks 代理
Typora配合PicGo阿里云图床配置
SoapUI、Jmeter、Postman三种接口测试工具的
github用相对路径显示图片_GitHub 中 readm
Windows编译g2o及其g2o viewer
解决jupyter notebook无法连接/ jupyter连接
Git恢复到之前版本
VScode常用快捷键
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 18:57:14  更:2022-04-22 18:58:31 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/14 14:53:18-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码