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

810
2023/10/11 12:32:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在.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服务器的配置。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 用.NET开发的磁力搜索引擎——btbook.net