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;

}

}

}

相关推荐
Gerardisite11 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want59512 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan12 小时前
【C++】多态
开发语言·c++
gfdhy12 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Eiceblue13 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY13 小时前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
leon_zeng013 小时前
Qt Modern OpenGL 入门:从零开始绘制彩色图形
开发语言·qt·opengl
会飞的胖达喵13 小时前
Qt CMake 项目构建配置详解
开发语言·qt
ceclar12313 小时前
C++范围操作(2)
开发语言·c++
一个尚在学习的计算机小白13 小时前
java集合
java·开发语言