C# 发送邮件到多个收件人 - 简单易懂的示例代码
在 C# 中发送邮件到多个人,可以使用 SmtpClient 类来实现。以下是一个示例代码:
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main(string[] args)
{
string smtpServer = 'smtp.example.com'; // 设置SMTP服务器地址
int smtpPort = 587; // 设置SMTP服务器端口
string smtpUsername = 'your_username'; // 设置SMTP服务器用户名
string smtpPassword = 'your_password'; // 设置SMTP服务器密码
string[] recipients = { 'recipient1@example.com', 'recipient2@example.com' }; // 设置收件人邮箱地址
string sender = 'sender@example.com'; // 设置发件人邮箱地址
string subject = '邮件主题'; // 设置邮件主题
string body = '邮件内容'; // 设置邮件内容
// 创建MailMessage对象
MailMessage mail = new MailMessage();
// 设置发件人
mail.From = new MailAddress(sender);
// 设置收件人
foreach (string recipient in recipients)
{
mail.To.Add(recipient);
}
// 设置邮件主题和内容
mail.Subject = subject;
mail.Body = body;
// 创建SmtpClient对象并设置SMTP服务器信息
SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort);
smtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
smtpClient.EnableSsl = true;
try
{
// 发送邮件
smtpClient.Send(mail);
Console.WriteLine('邮件发送成功!');
}
catch (Exception ex)
{
Console.WriteLine('邮件发送失败:' + ex.Message);
}
}
}
请注意,你需要将代码中的 smtpServer、smtpPort、smtpUsername、smtpPassword、sender 和 recipients 替换为你自己的实际信息。另外,需要确保你的计算机可以访问指定的 SMTP 服务器。
原文地址: https://www.cveoy.top/t/topic/Ui6 著作权归作者所有。请勿转载和采集!