在C#中,编写代码,发送邮件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using System.Net.Configuration;
using System.Configuration;
using System.Web.Configuration;
namespace SendMailTest
{
public partial class SendMail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> receiveMailAddressList = initReceiveMailAddress();
SendMailMessage(receiveMailAddressList);
}
/// <summary>
/// 初始化收件人的邮件地址
/// </summary>
/// <returns></returns>
private static List<string> initReceiveMailAddress()
{
List<string> receiveMailAddressList = new List<string>();
receiveMailAddressList.Add("chaii@.cn");
receiveMailAddressList.Add("liu@111.cn");
receiveMailAddressList.Add("song@222t.cn");
return receiveMailAddressList;
}
/// <summary>
/// 发送邮件消息
/// </summary>
public static void SendMailMessage(List<string> receiveMailAddressList)
{
if (receiveMailAddressList != null && receiveMailAddressList.Count > 0)
{
MailMessage mailMessage = new MailMessage();
//设置发件人的邮件地址
MailAddress senderMailAddress = new MailAddress("chai@.cn");
//添加发件人的邮件地址
mailMessage.From = senderMailAddress;
//添加收件人的邮件地址
foreach (string mailAddress in receiveMailAddressList)
{
MailAddress receiveMailAddress = new MailAddress(mailAddress);
mailMessage.To.Add(receiveMailAddress);
}
//设置邮件的主题
mailMessage.Subject = "邮件订阅测试";
mailMessage.SubjectEncoding = Encoding.UTF8;
//设置邮件的正文
mailMessage.Body = "测试一下邮件群发的功能,别紧张@";
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.IsBodyHtml = true;
//设置邮件的优先级别
mailMessage.Priority = MailPriority.High;
//读取WebConfig配置文件中的数据
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
//发送电子邮件
SmtpClient smtpClient = new SmtpClient();
//设置用于 SMTP 事务的主机的名称,填IP地址也可以了
smtpClient.Host = settings.Smtp.Network.Host;
//设置用于 SMTP 事务的端口,默认的是 25
smtpClient.Port = settings.Smtp.Network.Port;
//设置登录邮箱的用户名和密码
smtpClient.Credentials = new System.Net.NetworkCredential(settings.Smtp.Network.UserName,
settings.Smtp.Network.Password);
//指定如何处理待发的电子邮件,电子邮件通过网络发送到 SMTP 服务器
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
//是否使用安全套接字层 (SSL) 加密连接
smtpClient.EnableSsl = settings.Smtp.Network.EnableSsl;
//发送电子邮件
try
{
smtpClient.Send(mailMessage);
MessageBox.Show("您的邮件已发送成功", "发送成功");
}
catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show(ex.Message, "发送失败");
}
}
}
}
}