本文介绍了通过 Gmail 在 .NET 中发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有依靠主机发送电子邮件,而是考虑使用我的 Gmail 帐户发送电子邮件.这些电子邮件是发给我在演出中演奏的乐队的个性化电子邮件.
Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.
可以吗?
推荐答案
请务必使用 System.Net.Mail
,而不是已弃用的 System.Web.Mail
.使用 System.Web.Mail
执行 SSL 是一堆乱七八糟的扩展.
Be sure to use System.Net.Mail
, not the deprecated System.Web.Mail
. Doing SSL with System.Web.Mail
is a gross mess of hacky extensions.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
另外转到 Google 帐户 >安全页面,然后查看登录 Google >两步验证设置.
- 如果已启用,则您必须生成一个密码,允许 .NET 绕过两步验证.为此,请点击登录 Google >应用密码,选择app=Mail,设备=Windows Computer,最后生成密码.使用
fromPassword
常量中生成的密码,而不是标准的 Gmail 密码. - 如果它被禁用,那么您必须开启安全性较低的应用访问,不推荐!所以最好启用两步验证.
- If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the
fromPassword
constant instead of your standard Gmail password. - If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.
这篇关于通过 Gmail 在 .NET 中发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!