从列表框C#发送多封电子邮件可以通过以下步骤实现:
MailMessage mail = new MailMessage();
mail.From = new MailAddress("sender@example.com");
foreach (var recipient in selectedRecipients)
{
mail.To.Add(new MailAddress(recipient));
}
mail.Subject = "邮件主题";
mail.Body = "邮件正文";
mail.IsBodyHtml = true; // 如果需要发送HTML格式的邮件正文
Attachment attachment = new Attachment("文件路径");
mail.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.example.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true; // 如果需要使用SSL加密连接
smtpClient.Credentials = new NetworkCredential("username", "password");
smtpClient.Send(mail);
完整的代码示例:
using System.Net.Mail;
using System.Net;
// 获取选中的收件人列表
List<string> selectedRecipients = new List<string>();
foreach (var item in listBox.SelectedItems)
{
selectedRecipients.Add(item.ToString());
}
// 创建电子邮件对象
MailMessage mail = new MailMessage();
mail.From = new MailAddress("sender@example.com");
foreach (var recipient in selectedRecipients)
{
mail.To.Add(new MailAddress(recipient));
}
mail.Subject = "邮件主题";
mail.Body = "邮件正文";
mail.IsBodyHtml = true;
// 添加附件(可选)
Attachment attachment = new Attachment("文件路径");
mail.Attachments.Add(attachment);
// 配置SMTP服务器
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.example.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential("username", "password");
// 发送邮件
smtpClient.Send(mail);
注意:以上示例中的SMTP服务器地址、端口号、用户名、密码等需要根据实际情况进行配置。另外,为了确保邮件正常发送,需要确保本地计算机可以访问SMTP服务器,并且SMTP服务器允许使用给定的用户名和密码进行身份验证。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云