在C#中,使用Exchange Web Services (EWS) API實現郵件加密的方法如下:
Install-Package Microsoft.Exchange.WebServices.NETStandard
using Microsoft.Exchange.WebServices.Data;
using System.Security.Cryptography.X509Certificates;
private static X509Certificate2 LoadCertificate(string certificatePath, string password)
{
return new X509Certificate2(certificatePath, password);
}
public static void SendEncryptedEmail(string smtpAddress, string emailSubject, string emailBody, string toRecipient, string certificatePath, string certificatePassword)
{
// 加載證書
X509Certificate2 certificate = LoadCertificate(certificatePath, certificatePassword);
// 設置Exchange服務
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new WebCredentials(smtpAddress, "your_password", "your_domain");
service.Url = new Uri("https://your_exchange_server/ews/exchange.asmx");
// 創建電子郵件
EmailMessage message = new EmailMessage(service);
message.Subject = emailSubject;
message.Body = new MessageBody(BodyType.HTML, emailBody);
message.ToRecipients.Add(toRecipient);
// 加密郵件
message.Encrypt(new X509Certificate2Collection(certificate));
// 發送郵件
message.SendAndSaveCopy();
}
SendEncryptedEmail
函數發送加密郵件:string smtpAddress = "sender@example.com";
string emailSubject = "Encrypted Email Test";
string emailBody = "<html><body>This is a test of encrypted email using C#.</body></html>";
string toRecipient = "recipient@example.com";
string certificatePath = @"C:\path\to\certificate.pfx";
string certificatePassword = "your_certificate_password";
SendEncryptedEmail(smtpAddress, emailSubject, emailBody, toRecipient, certificatePath, certificatePassword);
注意:請將示例代碼中的占位符替換為實際值,例如"your_password"、“your_domain"和"https://your_exchange_server/ews/exchange.asmx”。同時,確保提供有效的證書路徑和密碼。