C# 调用示例

最近更新时间:2024-12-23 14:14:22

我的收藏
由于官方库对465、587端口的支持不完善,推荐使用以下示例中的第三方库 MailKit
using System;
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;

// This code example uses MailKit (MIT License: https://github.com/jstedfast/MailKit)

class Program
{
static void Main()
{
try
{
//控制台创建的发信地址
string fromEmail = "test@example.com";
//控制台设置的SMTP密码
string password = "your password";
string toEmail = "to@example.com";
string smtpHost = "smtp.qcloudmail.com";
int smtpPort = 465;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("", fromEmail));
message.To.Add(new MailboxAddress("", toEmail));
message.Subject = "Test Email with HTML Content";
message.Body = new TextPart("html")
{
Text = @"
<html>
<body>
<h1 style='color:blue;'>Hello!</h1>
<p>This is a <b>HTML test email</b> from <i>Tencent Cloud SES</i>.</p>
<p>Visit <a href='https://cloud.tencent.com/'>this link</a> for more info.</p>
</body>
</html>"
};

using (var client = new SmtpClient())
{
client.Connect(smtpHost, smtpPort, SecureSocketOptions.SslOnConnect);
client.Authenticate(fromEmail, password);
client.Send(message);
client.Disconnect(true);
}

Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}