ASP.NET CORE
.NET Core寄信範例,最近在用google gmail smtp發現他要二道驗證方式...
請先到二道式驗證,在申請應用程式密碼
目前我是先用MailKit和Mimekit套件,來做寄信...
using System;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace EmailDemo
{
class Program
{
static async Task Main(string[] args)
{
await new EmailSender().SendAsync("bda605@gmail.com", "測試", "測試");
}
}
public class EmailSender : ISender
{
public async Task SendAsync(string email, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("測試標題", "bda605@gmail.com"));
emailMessage.To.Add(new MailboxAddress(email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("html") { Text = message };
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.gmail.com", 587, false).ConfigureAwait(false);
client.Authenticate("bda605@gmail.com", "");
await client.SendAsync(emailMessage).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
public interface ISender
{
Task SendAsync(string email, string subject, string message);
}
}
元哥的筆記