You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 4.5下Gmail账号用SmtpClient发邮件遇错误及HttpClient用法求助

解决Gmail SMTP报错及.NET 4.5用HttpClient发邮件方案

一、解决当前SmtpClient报错问题

报错Unable to read data from the transport connection: net_io_connectionclosed核心原因是.NET 4.5默认未启用TLS 1.2,而Gmail要求使用TLS 1.2及以上版本加密连接。只需在代码中添加一行启用TLS1.2的配置:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

修改后的完整代码:

MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress(smtp.FromEmail, smtp.FromName);
message.To.Add(new MailAddress(dto.To));
message.Subject = dto.Subject;
message.Body = dto.Body;

// 启用TLS 1.2,必须放在创建SmtpClient之前
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

using (var client = new SmtpClient(smtp.Host, smtp.Port.Value))
{
    client.Credentials = new NetworkCredential(smtp.UserName, smtp.Password);
    client.EnableSsl = true;

    try
    {
        client.Send(message);
    }
    catch (Exception)
    {
        throw;
    }
}

额外确认项:

  • 确保smtp.Host设置为smtp.gmail.com
  • 端口465为Gmail SSL连接的正确端口
  • 应用专用密码是对应目标Gmail账号生成的有效密码

二、.NET 4.5中使用HttpClient发送Gmail邮件

HttpClient本身不支持SMTP协议,需通过调用Gmail API实现,步骤如下:

1. 安装NuGet包

在NuGet包管理器中安装以下两个包:

  • Google.Apis.Gmail.v1
  • Google.Apis.Auth

2. 获取OAuth 2.0凭据

前往Google Cloud控制台,完成以下操作:

  • 创建新项目并启用Gmail API
  • 创建OAuth客户端ID(类型选择「桌面应用」)
  • 下载凭据文件(JSON格式),命名为credentials.json并存放在项目目录

3. 代码实现

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using System.IO;
using System.Net.Mail;
using System.Threading;

// 加载OAuth凭据文件
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
    string tokenPath = "token.json";
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { GmailService.Scope.GmailSend },
        "user",
        CancellationToken.None,
        new FileDataStore(tokenPath, true)).Result;
}

// 初始化Gmail服务
var gmailService = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "你的应用名称",
});

// 构造邮件内容
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress("你的Gmail账号@gmail.com");
mailMessage.To.Add("收件人邮箱@xxx.com");
mailMessage.Subject = "测试邮件主题";
mailMessage.Body = "<h1>测试邮件内容</h1>";
mailMessage.IsBodyHtml = true;

// 将MailMessage转换为Gmail API要求的Base64编码格式
byte[] mailBytes;
using (var ms = new MemoryStream())
{
    mailMessage.WriteTo(ms);
    mailBytes = ms.ToArray();
}
string rawMail = Convert.ToBase64String(mailBytes)
    .Replace('+', '-')
    .Replace('/', '_')
    .Replace("=", "");

// 调用Gmail API发送邮件
var apiMessage = new Message { Raw = rawMail };
gmailService.Users.Messages.Send(apiMessage, "me").Execute();

说明:

  • 首次运行会弹出浏览器引导你授权目标Gmail账号,授权后生成token.json文件,后续运行无需重复授权
  • 代码中的"me"代表当前授权的用户账号,无需替换为具体邮箱地址

内容的提问来源于stack exchange,提问作者Qba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:41:22