| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
-
- using MailKit.Net.Smtp;
- using MailKit.Security;
- using MimeKit;
- namespace OASystem.API.OAMethodLib.HotmailEmail
- {
- /// <summary>
- /// Hotemail 服务
- /// </summary>
- public class HotmailEmailService : IHotmailEmailService
- {
- private readonly IConfiguration _configuration;
- public HotmailEmailService(IConfiguration configuration)
- {
- _configuration = configuration;
- }
- public async Task<bool> SendEmailAsync(string toEmail, string subject, string htmlContent)
- {
- // 从配置读取信息
- var smtpServer = _configuration["HotEmailConfig:SmtpServer"];
- var smtpPort = int.Parse(_configuration["HotEmailConfig:SmtpPort"]);
- var senderEmail = _configuration["HotEmailConfig:SenderEmail"];
- var senderName = _configuration["HotEmailConfig:SenderName"];
- var appPassword = _configuration["HotEmailConfig:AppPassword"];
- var message = new MimeMessage();
- message.From.Add(new MailboxAddress(senderName, senderEmail));
- message.To.Add(new MailboxAddress("", toEmail));
- message.Subject = subject;
- var bodyBuilder = new BodyBuilder { HtmlBody = htmlContent };
- message.Body = bodyBuilder.ToMessageBody();
- using var client = new SmtpClient();
- try
- {
- // 连接服务器 (Hotmail/Outlook 必须使用 StartTls)
- await client.ConnectAsync(smtpServer, smtpPort, SecureSocketOptions.StartTls);
- // 身份验证
- await client.AuthenticateAsync(senderEmail, appPassword);
- // 执行发送
- await client.SendAsync(message);
- await client.DisconnectAsync(true);
- return true;
- }
- catch (Exception ex)
- {
- // 这里可以记录到你的 OASystem 日志库
- Console.WriteLine($"[Email Error]: {ex.Message}");
- return false;
- }
- }
- }
- }
|