.NET Coreにおけるメール送信の実装方法

.NET Coreでメールを送信するには、System.Net.Mail.SmtpClientクラスを使用できます。メールを送信するサンプルコードを以下に示します。

using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main()
{
// 发件人邮箱地址
string from = "sender@example.com";
// 发件人邮箱密码(或授权码)
string password = "password";
// 收件人邮箱地址
string to = "recipient@example.com";
// 邮件主题
string subject = "Hello from .NET Core";
// 邮件内容
string body = "This is a test email.";
// 创建一个SmtpClient对象
SmtpClient client = new SmtpClient("smtp.example.com", 587);
// 设置使用的SMTP服务器地址和端口号
client.EnableSsl = true; // 如果SMTP服务器要求SSL连接,请设置为true
// 设置发件人邮箱地址和密码
client.Credentials = new NetworkCredential(from, password);
// 创建一个MailMessage对象
MailMessage message = new MailMessage(from, to, subject, body);
try
{
// 发送邮件
client.Send(message);
Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine("Failed to send email: " + ex.Message);
}
}
}

`from`、`password`、`to`、`subject`、`body`の変数の値を設定することで、メールを送信できます。smtp.example.comは、使用するSMTPサーバのアドレスに変更し、必要に応じて他のSMTPサーバの設定を行ってください。

bannerAds