using System;
using System.Net;
using System.Net.Mail;
public class EmailSender
{
public void SendEmail(string toAddress, string subject, string body)
{
// 设置发件人邮箱地址以及授权码
string fromAddress = "xxxxx@qq.com";
string password = "wxxxxxdgtdzhecjb";
// 创建邮件消息对象
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = body;
// 创建SMTP客户端对象,设置SMTP服务器和端口号(这里不用改)
SmtpClient smtpClient = new SmtpClient("smtp.qq.com", 587);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromAddress, password);
smtpClient.EnableSsl = true;
try
{
// 发送邮件
smtpClient.Send(mail);
Console.WriteLine("邮件发送成功!");
}
catch (Exception ex)
{
Console.WriteLine("发送邮件时出现错误: " + ex.Message);
}
}
}
public class Test
{
static int Main(string[] args)
{
EmailSender emailSender = new EmailSender();
emailSender.SendEmail("yyyyyyy@qq.com", "测试邮件", "这是一封测试邮件");//发送地址、邮箱标题、邮箱内容
return 0;
}
}
申请授权码:
第一步,登录QQ邮箱,点击设置-账号-找到下图位置点击开启服务
第二步,按照步骤指引,发送短信
第三步,记住授权码(后续无法查看授权码,但是可以生成多个授权码,不该邮箱密码不会过期)