Asp.net core 发送邮件

Asp.net core 发送邮件


在开始之前,先做好准备工作
在配置文件中设置好发送邮件的基本信息,在 appsettings.json中添加:

 "NotificationMetadata": {
    "Sender": "wenjie.1223@qq.com",
    "SmtpServer": "smtp.qq.com",
    "Port": 465,
    "Username": "wenjie.1223@qq.com",
    "Password": "pssword"
  }

Startup.csConfigureServices注册:

public void ConfigureServices(IServiceCollection services)
        {
            var notificationMetadata = Configuration.GetSection("NotificationMetadata").Get<NotificationMetadata>();
            services.AddSingleton(notificationMetadata);
            services.AddControllersWithViews();
        }

创建ModelNotificationMetadata类:

  public class NotificationMetadata
    {
        public string Sender { get; set; }
        public string SmtpServer { get; set; }
        public int Port { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

EmailMessage类:

 public class EmailMessage
    {
        public MailboxAddress Sender { get; set; }
        public string Subject { get; set; }
        public string Reciever { get; set; }
        public string Content { get; set; }

        public static MimeMessage CreateEmailMessage(EmailMessage message)
        {
            var mimeMessage = new MimeMessage();
            mimeMessage.From.Add(message.Sender);
            mimeMessage.Subject = message.Subject;
            // 支持Html和text文本格式
            mimeMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html)
            { Text = message.Content };
            return mimeMessage;
        }
    }

Controllers中添加构造方法:

private NotificationMetadata _notificationMetadata;

public MailController(NotificationMetadata notificationMetadata)
{
	this._notificationMetadata = notificationMetadata;
}

使用自带的SmtpClient

 public string sendEmail()
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(_notificationMetadata.Sender, "System");
            // 输入发送的人
            mailMessage.To.Add(new MailAddress("email_address"));
            // 输入cc的人,如果有多个可以多次Add
            mailMessage.CC.Add(new MailAddress("email_address"));
            mailMessage.CC.Add(new MailAddress("email_address"));
            mailMessage.Subject = "这是邮件的标题";
            StringBuilder sb = new StringBuilder();
            sb.Append("这是邮件的内容");
            mailMessage.Body = sb.ToString();
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.BodyEncoding = Encoding.UTF8;
            SmtpClient client = new SmtpClient();
            client.Host = _notificationMetadata.SmtpServer;
            client.Port = _notificationMetadata.Port;
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(_notificationMetadata.UserName, _notificationMetadata.Password);
            try
            {
                client.Send(mailMessage);
                return "邮件已发送,请注意查收!";
            }
            catch (Exception ex)
            {

                return ex.ToString();
            }
        }

使用MimeKit

 public string sendEmailMimeKit()
        {
            EmailMessage message = new EmailMessage();
            message.Sender = new MailboxAddress("System", _notificationMetadata.Sender);
            message.Subject = "";
            message.Content = "";
            var mimeMessage = EmailMessage.CreateEmailMessage(message);
            mimeMessage.To.Add(address: new MailboxAddress(""));            
            using (SmtpClient smtpClient = new SmtpClient())
            {
                smtpClient.Connect(_notificationMetadata.SmtpServer,
                _notificationMetadata.Port, useSsl:true);
                smtpClient.Authenticate(_notificationMetadata.UserName,
                _notificationMetadata.Password);
                try
                {
                    smtpClient.Send(mimeMessage);
                    smtpClient.Disconnect(true);
                    return "邮件已发送,请注意查收!";
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
        }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 ASP.NET Core 中使用 MailKit 发送电子邮件,需要执行以下步骤: 1. 安装 MailKit 和 MimeKit NuGet 包。 2. 在 Startup.cs 文件中添加以下代码: ```csharp using MailKit.Net.Smtp; using MimeKit; public void ConfigureServices(IServiceCollection services) { // ... services.AddMailKit(optionBuilder => { optionBuilder.UseSmtp("smtp.gmail.com", 587); optionBuilder.EnableSsl = true; optionBuilder.AuthenticationOptions = AuthenticationOptions.DoNotAuthenticate; }); // ... } ``` 3. 在控制器或服务中注入 `IMailer` 接口。 ```csharp using MailKit.Net.Smtp; using MimeKit; public class MyController : Controller { private readonly IMailer _mailer; public MyController(IMailer mailer) { _mailer = mailer; } public async Task<IActionResult> SendEmail() { var message = new MimeMessage(); message.From.Add(new MailboxAddress("From Name", "from@example.com")); message.To.Add(new MailboxAddress("To Name", "to@example.com")); message.Subject = "Test Email"; message.Body = new TextPart("plain") { Text = "This is a test email." }; await _mailer.SendAsync(message); return Ok(); } } ``` 4. 通过 MailKit 发送电子邮件: ```csharp using MailKit.Net.Smtp; using MimeKit; public interface IMailer { Task SendAsync(MimeMessage message); } public class Mailer : IMailer { private readonly SmtpClient _smtpClient; public Mailer(SmtpClient smtpClient) { _smtpClient = smtpClient; } public async Task SendAsync(MimeMessage message) { await _smtpClient.SendAsync(message); } } ``` 现在,当执行 `SendEmail()` 方法时,将通过 MailKit 发送电子邮件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值