QQ 邮箱 SMTP 发送邮件 C#.Net 代码(适配 VS2015,.NET Framework)
|
admin
2026年9月10日 19:2
本文热度 46
|
环境说明:VS2015 默认使用 .NET Framework,QQ 邮箱 SMTP 服务器:smtp.qq.com,端口 587(TLS 加密,推荐),不要用 25 端口(国内运营商大多封禁)
重要:QQ 邮箱不能直接用 QQ 邮箱密码,需要去 QQ 邮箱网页端开启【POP3/IMAP/SMTP 服务】,生成授权码,代码里密码位置填这个授权码。
完整代码
using System;
using System.Net;
using System.Net.Mail;
namespace QQSmtpMailDemo
{
class Program
{
static void Main(string[] args)
{
try
{
// ========== 配置区,请修改下面参数 ==========
string smtpServer = "smtp.qq.com";
int smtpPort = 587;
string sendMailAccount = "你的QQ邮箱@qq.com"; // 发件邮箱
string authCode = "QQ邮箱生成的授权码"; // 不是QQ登录密码!
string receiveMail = "test@clicksun.cn"; // 收件邮箱
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress(sendMailAccount, "发件人名称");
mailMsg.To.Add(receiveMail);
mailMsg.Subject = "测试邮件标题";
mailMsg.Body = "这是一封来自C#程序的SMTP测试邮件";
mailMsg.IsBodyHtml = false; // 如果邮件内容是HTML,改为true
SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort);
smtpClient.Credentials = new NetworkCredential(sendMailAccount, authCode);
smtpClient.EnableSsl = true; // 587端口必须开启SSL/TLS
Console.WriteLine("正在发送邮件...");
smtpClient.Send(mailMsg);
Console.WriteLine("✅ 邮件发送成功!");
// 释放资源
mailMsg.Dispose();
smtpClient.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("❌ 发送失败:" + ex.Message);
}
Console.ReadKey();
}
}
}
项目引用说明(VS2015)
新建 控制台应用 (.NET Framework),项目默认已经自带 System.Net 和 System.Net.Mail,无需额外安装 NuGet 包。
QQ 邮箱授权码获取步骤
- 登录网页版 QQ 邮箱 → 设置 → 账户
- 找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV 服务
- 开启 POP3/SMTP 服务,按短信验证,生成授权码,复制保存。
常见报错排查
- 535 Error: authentication failed:授权码填错,或者没有开启 SMTP 服务
- 连接超时:防火墙拦截,或者错误使用 25 端口;优先使用 587 端口 + EnableSsl=true
- VS2015 .NET Framework 4.0/4.5 TLS 版本问题:
如果报 不支持此安全协议,在代码最开头增加安全协议设置:
// 在Main方法最顶部添加,兼容老.NET Framework(VS2015)
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
需要引用命名空间:using System.Net;
添加后完整 Main 开头示例:
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
try
{
// ...原有代码
}
可选扩展:添加附件
// 添加附件
Attachment attach = new Attachment(@"D:\test.txt");
mailMsg.Attachments.Add(attach);
该文章在 2026/9/10 19:03:14 编辑过