C# 发送邮件

news/2024/12/22 3:00:49/

1.安装 NuGet 包

2.代码如下

SendMailUtil

using MimeKit;
using Srm.CMER.Application.Contracts.CmerInfo;

namespace Srm.Mail
{
    public class SendMailUtil
    {
        public async static Task<string> SendEmail(SendEmialDto sendEmialDto,List<string> tolist, List<string> cclist, BodyBuilder builder, string title, CancellationToken cancellationToken)
        {

            // MimeMessage可以堪称MailKit里的一个邮件对象
            var sendMessage = new MimeMessage();    

            sendMessage.Subject = title;

            // 也可以添加多个发件人,二选其一
            //   sendMessage.From.Add(new MailboxAddress(data.Name, data.Address));
            // sendMessage.From.Add(new MailboxAddress("2799788752", "2799788752@qq.com"));
                sendMessage.From.Add(new MailboxAddress(sendEmialDto.UserName, sendEmialDto.Eamil));
            // 添加收件人信息


            string mailtos = string.Empty;
            foreach (var it in tolist)
            {
                if (!it.IsNullOrEmpty())
                {
                    if (mailtos.IsNullOrEmpty())
                    {
                        mailtos = it + ";";
                    }
                    else
                    {
                        mailtos += it + ";";
                    }
                    sendMessage.To.Add(new MailboxAddress(it, it));
                }
            }

            // 添加抄送(CC)人信息
            string mailccs = string.Empty;
            foreach (var it in cclist)
            {
                if (!it.IsNullOrEmpty())
                {
                    if (mailccs.IsNullOrEmpty())
                    {
                        mailccs = it + ";";
                    }
                    else
                    {
                        mailccs += it + ";";
                    }
                    if (it.Contains(";"))
                    {
                        string[] emial = it.Split(';');
                        foreach (string s in emial)
                        {
                            sendMessage.Cc.Add(new MailboxAddress(s, s));
                        }
                    }
                    else
                    {
                        sendMessage.Cc.Add(new MailboxAddress(it, it));
                    }

                }

            }
            //sendMessage.Cc.Add(new MailboxAddress("gyn", "gaoyanan@jshzxx.com"));

            // 邮件正文两种形式
            // 1. 不带附件
            // html
            sendMessage.Body= builder.ToMessageBody();
             
           //sendMessage.Body = new TextPart(TextFormat.Html) { Text = builder.HtmlBody };
            // 或者纯文本
        //    sendMessage.Body = new TextPart(TextFormat.Plain) { Text = context };

            // 2. 带附件
            /*var builder = new BodyBuilder();
            builder.TextBody = "邮件正文文字描述";
            // 添加附件,需带完整路径或者相对路径
            builder.Attachments.Add("test.xlsx");
            sendMessage.Body = builder.ToMessageBody();*/

            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                try
                {
                    // 1. 注册邮件发送成功之后的事件,比如记录log
                    // MessageSent事件里可以通过args参数,获得服务器的响应信息,以便于记录Log。
                    smtp.MessageSent += (sender, args) => {
                        //  args.Response;

                    };
                    smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    // 2. 连接服务器
                    //if (sendEmialDto.AccountName == "forehopetcs@forehope-elec.com")
                    //{
                        await smtp.ConnectAsync("smtp.exmail.qq.com", 465, true, cancellationToken);
                    //}
                    //else
                    //{
                    //    await smtp.ConnectAsync("smtp.qq.com", 465, true, cancellationToken);
                    //}
                    // 3. 验证账号
                    //    await smtp.AuthenticateAsync(data.UserName, data.MailPassword, cancellationToken);

                    //  await smtp.AuthenticateAsync("2799788752", "qrjozanttznpdeei", cancellationToken);
                    await smtp.AuthenticateAsync(sendEmialDto.AccountName, sendEmialDto.AuthCode, cancellationToken);
                    // 4. 发送邮件
                    var success = await smtp.SendAsync(sendMessage, cancellationToken);
                    // 5. 释放链接
                    await smtp.DisconnectAsync(true, cancellationToken);

                    return success;
                }
                catch (Exception e)
                {
                    return e.Message;
                }
            }
        }
    }
}

SendEmialDto

namespace Srm.CMER.Application.Contracts.CmerInfo
{
    public class SendEmialDto
    {
        //账号名
        public string? AccountName { get; set; }
        //email
        public string? Eamil { get; set; }
        //授权码
        public string? AuthCode { get; set; }
        //用户名
        public string? UserName { get; set; }

    }
}

示例

SendEmailCommand

using System;
using System.Data;
using AutoMapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MimeKit;
using Srm.CMER.Application.Contracts.CmerInfo;
using Srm.COC.Application.Contracts.SpecApprove;
using Srm.Config;
using Srm.Core.Application.Commands;
using Srm.Core;
using Srm.Mail;
using Srm.Autofac;
using Srm.COC.Application.Contracts.Spec;

namespace Srm.Audit.Application.AuditFindings.Commands
{
    public class SendEmailCommand : IRequest<bool>
    {
        public string SupplierName { get; }

        public SendEmailCommand(string supplierName)
        {
            this.SupplierName = supplierName;
        }
    }
    public class SendEmailCommandHandler : CommandRequestHandler<SendEmailCommand, bool>
    {
        public SendEmailCommandHandler(IMediator mediator, IMapper mapper, IDbContext dbContext) : base(mediator, mapper, dbContext)
        {
        }

        public override async Task<bool> HandleAsync(SendEmailCommand request, IDbConnection dbConnection, CancellationToken cancellationToken)
        {
            string module = "供应商稽核";
            //收件人
            var tolist = new List<string>();

            SendEmialDto sendEmailDto = new SendEmialDto();
            sendEmailDto.AuthCode = "Foref7!00HopeTCS";
            sendEmailDto.AccountName = "forehopetcs@forehope-elec.com";
            sendEmailDto.Eamil = "forehopetcs@forehope-elec.com";
            sendEmailDto.UserName = "供应商管理系统(甬矽电子)";

            IConfiguration confing = SrmConfig.GetConfig();
            IConfigurationSection HttpUrlSection = confing.GetSection("GradeURL");
            string httpUrl = HttpUrlSection["HTTPURL"];

            var builder = new BodyBuilder();

            builder.TextBody += request.SupplierName+ "  ,请登录供应商系统("+httpUrl+")完成FINDINGS的填写,系统邮件无需回复,谢谢。";

            var SpecApproveQueryService = ServiceLocator.GetService<ISpecApproveQueryService>();
            var SpecQueryService = ServiceLocator.GetService<ISpecQueryService>();
            List<string> sqeemail = await SpecQueryService.GetSqeEmailsByModule(request.SupplierName,module, cancellationToken);
         
            List<string> SupplierEmails = await SpecApproveQueryService.GetSupEmailbyModule(request.SupplierName, module, cancellationToken);
            List<string> supccemail=await SpecApproveQueryService.GetSupccemail(request.SupplierName,module, cancellationToken);
            // 邮箱
            tolist.AddRange(SupplierEmails);
        
            var cclist=new List<string>();
            if (supccemail.Count > 0)
            {
                cclist.AddRange(supccemail);
            }
            if (sqeemail.Count < 1)
            {
                List<string> sqeemailTotal = await SpecQueryService.GetSqeEmails(cancellationToken);
                sqeemail.AddRange(sqeemailTotal);
            }
            cclist.AddRange(sqeemail);
            await SendMailUtil.SendEmail(sendEmailDto, tolist,cclist, builder, "FINDINGS提醒", cancellationToken);
            return true;
        }

    }
}


http://www.ppmy.cn/news/1194572.html

相关文章

MFC网络通信-Udp服务端

目录 1、UI的布局 2、代码的实现&#xff1a; &#xff08;1&#xff09;、自定义的子类CServerSocket &#xff08;2&#xff09;、重写OnReceive事件 &#xff08;3&#xff09;、在CUdpServerDlg类中处理 &#xff08;4&#xff09;、在OnInitDialog函数中 &#xff0…

Notes/Domino中的JVM版本

大家好&#xff0c;才是真的好。 这篇内容主要写给同时关注Domino和Java的技术人员。 很多人都知道&#xff0c;从Notes/Domino R5&#xff08;1999年&#xff09;版本&#xff0c;开始自带一个Java虚拟机&#xff0c;用来支持Java应用运行。但很多人不知道&#xff0c;这个J…

Dotfiles 管理最佳实践

背景介绍 在Unix和类Unix操作系统中&#xff0c;"dotfiles"是以点&#xff08;.&#xff09;开头的文件或目录的通用术语。这些文件通常用于存储用户特定的配置信息、设置和个人数据。点作为文件名的前缀表明这些文件是隐藏的&#xff0c;不会在普通的文件列表中显示…

2023年11月 AI速递

简介 微软在人工智能教育方面又出力作。generative-ai-for-beginners 包含一系列关于生成式人工智能的课程&#xff0c;包括 LLM 介绍、提示工程基础、构建文本生成/聊天应用等。 链接 https://github.com/microsoft/generative-ai-for-beginners 简介 中科大等机构的研究…

分享四款简单实用的视频下载工具

今天来和大家分享几个视频下载工具。毕竟&#xff0c;在这个自媒体时代&#xff0c;非常多的小伙伴有下载视频的需求&#xff0c;话不多说&#xff0c;直接上干货&#xff01; 1.Downni 这是一个在线视频下载网站。它支持几乎所有的主流视频平台&#xff1b;然后它还支持多种分…

ROS分布式演练,多台设备进行通信的配置

1、概述 前面我们做的操作都是在单个设备上进行&#xff0c;也就是分别开启多个终端&#xff0c;在不同终端上启动节点等相关操作&#xff0c;这里我们使用两台设备来控制&#xff0c;一台虚拟机和一台无人车(使用VNC Viewer连上去&#xff0c;也可以看做一台Linux虚拟机) VNC…

FFmpeg——使用Canvas录制视频尚存问题的解决方案

个人简介 &#x1f440;个人主页&#xff1a; 前端杂货铺 &#x1f64b;‍♂️学习方向&#xff1a; 主攻前端方向&#xff0c;正逐渐往全干发展 &#x1f4c3;个人状态&#xff1a; 研发工程师&#xff0c;现效力于中国工业软件事业 &#x1f680;人生格言&#xff1a; 积跬步…

【JavaScript】前端一定要看的 Promise 用法详细解析

每一个前端都要学的 Promise 用法详细解析 文章目录 前言一. 认识Promise1.1. 异步回调处理1.2. 什么是Promise1.3. Promise重构 二. Promise对象方法2.1. Executor2.2. then方法 2.2.1. then方法两个参数2.2.2. then方法多次调用2.2.3. then方法的返回值2.3. catch方法2.3.1.…