• C# 发送邮件


    1.安装 NuGet

    2.代码如下

    SendMailUtil

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

    namespace Srm.Mail
    {
        public class SendMailUtil
        {
            public async static Task SendEmail(SendEmialDto sendEmialDto,List tolist, List 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
        {
            public string SupplierName { get; }

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

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

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

        }
    }

  • 相关阅读:
    ts随记: ts配置文件详解 --webpack.config.js
    C#程序中很多ntdll.dll、clr.dll的线程
    操作系统面试题
    企业应用架构研究系列一:业务拆分
    SAP-MM-委外订单合并有什么不同?
    goland的Markdown拖动插入链接编码有问题
    AnimalTFDB v4.0 | OMG!我最爱的转录因子数据库更新啦!~(附使用指南)(二)
    凌恩客户文章|宏基因组揭示大蒜素对抗生素抗性基因的影响
    前端基础学习——你必须掌握的CSS的知识
    【分布式幂等性】高并发下如何保证接口的幂等性?
  • 原文地址:https://blog.csdn.net/weixin_56311692/article/details/134180084