102 lines
3.5 KiB
C#
102 lines
3.5 KiB
C#
using Microsoft.Extensions.Options;
|
|
using MimeKit;
|
|
using MimeKit.Text;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace New_College.Common.Helper
|
|
{
|
|
|
|
|
|
public static class MailKitManagement
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
/// send email
|
|
/// </summary>
|
|
/// <param name="toMailAddressList"></param>
|
|
/// <param name="ccAddresList"></param>
|
|
/// <param name="subject"></param>
|
|
/// <param name="body"></param>
|
|
/// <param name="attachmentList"></param>
|
|
/// <param name="isHtml"></param>
|
|
/// <returns></returns>
|
|
public static async Task SendMessageAsync(List<string> toMailAddressList, List<string> ccAddresList, string subject, string body, List<string> attachmentList = null, bool isHtml = false)
|
|
{
|
|
var mailMessage = new MimeMessage();
|
|
mailMessage.From.Add(new MailboxAddress(MailKitConfig.DisplayName, MailKitConfig.MailAddress));
|
|
foreach (var mailAddressItem in toMailAddressList)
|
|
{
|
|
mailMessage.To.Add(MailboxAddress.Parse(mailAddressItem));
|
|
}
|
|
if (ccAddresList != null)
|
|
{
|
|
ccAddresList.ForEach(p =>
|
|
{
|
|
mailMessage.Cc.Add(MailboxAddress.Parse(p));
|
|
});
|
|
}
|
|
|
|
mailMessage.Subject = subject;
|
|
TextPart messageBody = null;
|
|
if (isHtml)
|
|
{
|
|
messageBody = new TextPart(TextFormat.Html)
|
|
{
|
|
Text = body,
|
|
};
|
|
}
|
|
else
|
|
{
|
|
messageBody = new TextPart(TextFormat.Plain)
|
|
{
|
|
Text = body,
|
|
};
|
|
}
|
|
var mulitiPart = new Multipart("mixed")
|
|
{
|
|
};
|
|
mulitiPart.Add(messageBody);
|
|
if (attachmentList != null && attachmentList.Count > 0)
|
|
{
|
|
foreach (var attatchItem in attachmentList)
|
|
{
|
|
using (var stream = File.OpenRead(attatchItem))
|
|
{
|
|
var attachment = new MimePart()
|
|
{
|
|
Content = new MimeContent(stream, ContentEncoding.Default),
|
|
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
|
|
ContentTransferEncoding = ContentEncoding.Base64,
|
|
FileName = Path.GetFileName(attatchItem)
|
|
};
|
|
mulitiPart.Add(attachment);
|
|
}
|
|
}
|
|
}
|
|
mailMessage.Body = mulitiPart;
|
|
using (var client = new MailKit.Net.Smtp.SmtpClient())
|
|
{
|
|
if (MailKitConfig.IsSsl)
|
|
{
|
|
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
|
}
|
|
|
|
client.Connect(MailKitConfig.MailServer, MailKitConfig.SmtpPort, MailKitConfig.IsSsl);
|
|
|
|
// Disable the XOAUTH2 authentication mechanism.
|
|
//client.AuthenticationMechanisms.Remove("XOAUTH2");
|
|
|
|
// Note: only needed if the SMTP server requires authentication
|
|
client.Authenticate(MailKitConfig.MailAddress, MailKitConfig.Password);
|
|
await client.SendAsync(mailMessage);
|
|
client.Disconnect(true);
|
|
}
|
|
}
|
|
}
|
|
}
|