通过Gmail在.NET中发送电子邮件发送电子邮件、Gmail、NET

2023-09-02 01:16:11 作者:心里有座坟,住着未亡人

,我想送,虽然我的Gmail帐户的邮件。该电子邮件是个性化的电子邮件到我在我的节目玩乐队。是否有可能呢?

Instead of relying on my host to send email, I was thinking of sending the messages though my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do?

推荐答案

请务必使用 System.Net.Mail ,而不是去precated 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("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "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);
}