1.源码
` ///
/// SMTP发送邮箱(默认用QQ邮箱发送)
///
/// 收件人邮箱
/// 邮件主题
/// 邮件正文
/// host ----->QQ的为smtp.qq.com
/// port ----->QQ的为587
/// 是否添加附件
/// 添加附件路径
/// 是否抄送
/// 抄送地址 即抄送多个邮箱*/
public void SendEmail(string toAddress, string subject, string body, string host = "smtp.qq.com", int port = 587, bool IsfilePath=false, string filePath="",bool IsccAddresses=false, string[] ccAddresses=null)
{
try
{
MailMessage mailMessage = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
// 设置发件人邮箱
mailMessage.From = new MailAddress("[email protected]");
// 设置收件人邮箱
mailMessage.To.Add(toAddress);
// 设置邮件主题
mailMessage.Subject = subject;
// 设置邮件正文
mailMessage.Body = body;
if (IsfilePath)
{
// 添加附件(指定文件路径) 这里可以指定多个路径 每个都Add就可以了
Attachment attachment = new Attachment(filePath);
mailMessage.Attachments.Add(attachment);
}
if (IsccAddresses)
{
// 添加抄送地址
foreach (string ccAddress in ccAddresses)
{
mailMessage.CC.Add(new MailAddress(ccAddress));
}
}
// 设置SMTP服务器
smtpClient.Host = host; //"smtp.qq.com";
// 使用SSL加密
smtpClient.EnableSsl = true;
// 设置SMTP服务器端口
smtpClient.Port = port;//587; // 或者使用587
// 设置发件人邮箱的用户名和密码 --->密码是SMTP验证码
smtpClient.Credentials = new NetworkCredential("[email protected]", "123456789");
// 发送邮件
smtpClient.Send(mailMessage);
Console.WriteLine("邮件发送成功!");
}
catch (SmtpException ex)
{
Console.WriteLine("SMTP Exception: " + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("Inner Exception: " + ex.InnerException.Message);
}
}
catch (Exception ex)
{
Console.WriteLine("General Exception: " + ex.Message);
}
}
`
2.使用例子
private void button1_Click(object sender, EventArgs e) { SendEmail("[email protected]", "邮件主题", "邮件正文内容","smtp.qq.com", 587, true,"C:\\Users\\75252\\Desktop\\2024Test\\Source.bmp",false,new string[2]{"[email protected]","[email protected]"}); }