ASP.NET CORE发送邮件给多人
程序员文章站
2023-12-28 10:05:34
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class MailHelper
{
/// <summary>
/// 发送电子邮件
/// </summary>
/// <param name="smtpserver">SMTP服务器</param>
/// <param name="enableSsl">是否启用SSL加密</param>
/// <param name="userName">登录帐号</param>
/// <param name="pwd">登录密码</param>
/// <param name="nickName">发件人昵称</param>
/// <param name="fromEmail">发件人</param>
/// <param name="toMailArr">收件人集合</param>
/// <param name="subj">主题</param>
/// <param name="bodys">内容</param>
public async Task SendMailAsync(string[] toMailArr, string bodys)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
smtpClient.Host = "192.xxx.xxx.xxx";//指定SMTP服务器IP
smtpClient.Credentials = new NetworkCredential("邮箱账号", "邮箱密码");//发送人用户名和密码
smtpClient.EnableSsl = false;
MailAddress fromAddress = new MailAddress("[email protected]", "邮件标题");
//MailAddressCollection addressesArr = new MailAddressCollection();
MailMessage mailMessage = new MailMessage();
for (int i = 0; i < toMailArr.Length; i++)
{
//MailAddress toAddress = new MailAddress(toMailArr[i]);
//添加收件人邮箱
mailMessage.To.Add(new MailAddress(toMailArr[i]));
}
mailMessage.From = fromAddress;
//mailMessage.To.
//MailMessage mailMessage = new MailMessage(fromAddress, addressesArr);
mailMessage.Subject = subj;//主题
mailMessage.Body = bodys;//内容
mailMessage.BodyEncoding = Encoding.Default;//正文编码
mailMessage.IsBodyHtml = true;//设置为HTML格式
mailMessage.Priority = MailPriority.Normal;//优先级
await smtpClient.SendMailAsync(mailMessage);
}
}
}