温馨提示×

.net core之邮件发送怎么实现

小亿
139
2023-09-19 12:32:48
栏目: 编程语言

在.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);
}
}
}

通过设置frompasswordtosubjectbody变量的值,你可以发送邮件。请确保将smtp.example.com更改为你的SMTP服务器地址,并根据需要设置其他SMTP服务器的配置。

0