C# 发送邮件

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;

}

}

}

相关推荐
mazo_command17 分钟前
【MATLAB课设五子棋教程】(附源码)
开发语言·matlab
IT猿手21 分钟前
多目标应用(一):多目标麋鹿优化算法(MOEHO)求解10个工程应用,提供完整MATLAB代码
开发语言·人工智能·算法·机器学习·matlab
青春男大21 分钟前
java栈--数据结构
java·开发语言·数据结构·学习·eclipse
88号技师21 分钟前
几款性能优秀的差分进化算法DE(SaDE、JADE,SHADE,LSHADE、LSHADE_SPACMA、LSHADE_EpSin)-附Matlab免费代码
开发语言·人工智能·算法·matlab·优化算法
Zer0_on24 分钟前
数据结构栈和队列
c语言·开发语言·数据结构
一只小bit25 分钟前
数据结构之栈,队列,树
c语言·开发语言·数据结构·c++
一个没有本领的人1 小时前
win11+matlab2021a配置C-COT
c语言·开发语言·matlab·目标跟踪
一只自律的鸡2 小时前
C项目 天天酷跑(下篇)
c语言·开发语言
源码哥_博纳软云2 小时前
JAVA智慧养老养老护理帮忙代办陪诊陪护小程序APP源码
java·开发语言·微信小程序·小程序·微信公众平台
沐泽Mu2 小时前
嵌入式学习-QT-Day05
开发语言·c++·qt·学习