我想用我的Gmail帐户发送电子邮件,而不是依靠我的主机发送电子邮件。这些邮件是发给我在节目中演出的乐队的个性化邮件。

有可能做到吗?


当前回答

下面是一个从web.config发送邮件和获取凭证的方法:

public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
    try
    {
        System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
        newMsg.BodyEncoding = System.Text.Encoding.UTF8;
        newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
        newMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
        if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
            System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
            disposition.FileName = AttachmentFileName;
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

            newMsg.Attachments.Add(attachment);
        }
        if (test)
        {
            smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
        }
        else
        {
            //smtpClient.EnableSsl = true;
        }

        newMsg.IsBodyHtml = bodyHtml;
        smtpClient.Send(newMsg);
        return SENT_OK;
    }
    catch (Exception ex)
    {

        return "Error: " + ex.Message
             + "<br/><br/>Inner Exception: "
             + ex.InnerException;
    }

}

以及web.config中相应的部分:

<appSettings>
    <add key="mailCfg" value="yourmail@example.com"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="yourmail@example.com">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="yourmail@example.com" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

其他回答

一定要使用System.Net。邮件,而不是已弃用的System.Web.Mail。使用System.Web.Mail进行SSL是一堆拙劣的扩展。

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);
}

此外,转到谷歌帐户>安全页面,并查看登录谷歌> 2步验证设置。

如果启用了,那么您必须生成一个密码,允许. net绕过2步验证。点击“Signing in To谷歌> App passwords”,选择App = Mail, device = Windows Computer,最后生成密码。在fromPassword常量中使用生成的密码,而不是标准的Gmail密码。 如果它被禁用,那么你必须打开Less secure app access,这是不推荐的!所以最好启用两步验证。

我希望这段代码可以正常工作。你可以试试。

// Include this.                
using System.Net.Mail;

string fromAddress = "xyz@gmail.com";
string mailPassword = "*****";       // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";


// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);


// Fill the mail form.
var send_mail = new MailMessage();

send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("from@gmail.com");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("to@example.com");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);

编辑2022 从2022年5月30日起,谷歌将不再支持仅使用用户名和密码登录谷歌账户的第三方应用程序或设备。 但是你仍然可以通过你的gmail账户发送电子邮件。

访问https://myaccount.google.com/security,打开两步验证。如有需要,请电话确认。 点击“应用程序密码”,就在“2步验证”勾的下方。 请求邮件应用程序的新密码。

现在只需使用这个密码,而不是原来的一个为您的帐户!

public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) {            
            var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                EnableSsl = true
            };                
            smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
            var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
            smtpClient.Send(message);
    }

像这样使用:

SendMail2Step("smtp.gmail.com", 587, "youraccount@gmail.com",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "recipient@barcodes.bg", "test message subject", "Test message body ...", null);

对于其他答案工作“从服务器”首先打开访问gmail帐户不太安全的应用程序。这将在2022年5月30日被弃用

看来最近谷歌改变了安全策略。评分最高的答案不再有效,直到您更改您的帐户设置如下所述:https://support.google.com/accounts/answer/6010255?hl=en-GB 2016年3月,谷歌再次更改设置地点!

上面的答案不管用。必须设置DeliveryMethod = SmtpDeliveryMethod。网络,否则将返回“客户端未经过身份验证”错误。此外,暂停总是一个好主意。

修改后的代码:

using System.Net.Mail;
using System.Net;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

在Gmail / Outlook.com邮箱更改发件人:

为了防止欺骗- Gmail/Outlook.com不会让你从任意用户帐户名发送。

如果发件人数量有限,则可以按照以下说明将From字段设置为此地址:从不同地址发送邮件

如果你想从一个任意的电子邮件地址发送(比如用户在网站上输入他们的电子邮件,而你不希望他们直接给你发送电子邮件),你能做的最好的是:

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));

这可以让你在电子邮件账户中点击“回复”,在反馈页面上回复你乐队的粉丝,但他们不会收到你的实际电子邮件,这可能会导致大量垃圾邮件。

如果你在一个受控制的环境中,这工作得很好,但请注意,我看到一些电子邮件客户端发送到from地址,即使回复指定(我不知道是哪个)。