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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:11:18  来源:igfitidea点击:

Sending email in .NET through Gmail

提问by Mike Wills

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmailaccount. The emails are personalized emails to the bands I play on my show.

我没有依靠我的主机发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。这些电子邮件是发给我在演出中演奏的乐队的个性化电子邮件。

Is it possible to do it?

有可能做到吗?

采纳答案by Domenic

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mailis a gross mess of hacky extensions.

一定要使用System.Net.Mail,而不是弃用的System.Web.Mail. 使用 SSLSystem.Web.Mail是一堆乱七八糟的扩展。

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

回答by Donny V.

The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Networkor it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.

上面的答案不起作用。您必须进行设置,DeliveryMethod = SmtpDeliveryMethod.Network否则它会返回“客户端未通过身份验证”错误。此外,设置超时总是一个好主意。

Revised code:

修改后的代码:

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

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "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);
}

回答by tehie

Here is my version: "Send Email In C # Using Gmail".

这是我的版本:“使用 Gmail 在 C# 中发送电子邮件”。

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

namespace SendMailViaGmail
{
   class Program
   {
   static void Main(string[] args)
   {

      //Specify senders gmail address
      string SendersAddress = "[email protected]";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "[email protected]";
      //Specify The password of gmial account u are using to sent mail(pw of [email protected])
      const string SendersPassword = "Password";
      //Write the subject of ur mail
      const string subject = "Testing";
      //Write the contents of your mail
      const string body = "Hi This Is my Mail From Gmail";

      try
      {
        //we will use Smtp client which allows us to send email using SMTP Protocol
        //i have specified the properties of SmtpClient smtp within{}
        //gmails smtp server name is smtp.gmail.com and port number is 587
        SmtpClient smtp = new SmtpClient
        {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           Credentials    = new NetworkCredential(SendersAddress, SendersPassword),
           Timeout = 3000
        };

        //MailMessage represents a mail message
        //it is 4 parameters(From,TO,subject,body)

        MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
        /*WE use smtp sever we specified above to send the message(MailMessage message)*/

        smtp.Send(message);
        Console.WriteLine("Message Sent Successfully");
        Console.ReadKey();
     }

     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
     }
    }
   }
 }

回答by Ranadheer Reddy

This is to send email with attachement.. Simple and short..

这是发送带有附件的电子邮件..简单而简短..

source: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html

来源:http: //coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html

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

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your [email protected]");
    mail.To.Add("[email protected]");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

回答by Yasser Shaikh

Source: Send email in ASP.NET C#

来源在 ASP.NET C# 中发送电子邮件

Below is a sample working code for sending in a mail using C#, in the below example I am using google's smtp server.

下面是使用 C# 发送邮件的示例工作代码,在下面的示例中,我使用的是 google 的 smtp 服务器。

The code is pretty self explanatory, replace email and password with your email and password values.

该代码非常容易解释,用您的电子邮件和密码值替换电子邮件和密码。

public void SendEmail(string address, string subject, string message)
{
    string email = "[email protected]";
    string password = "put-your-GMAIL-password-here";

    var loginInfo = new NetworkCredential(email, password);
    var msg = new MailMessage();
    var smtpClient = new SmtpClient("smtp.gmail.com", 587);

    msg.From = new MailAddress(email);
    msg.To.Add(new MailAddress(address));
    msg.Subject = subject;
    msg.Body = message;
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = loginInfo;
    smtpClient.Send(msg);
}

回答by Simon_Weaver

Changing sender on Gmail / Outlook.com email:

更改 Gmail / Outlook.com 电子邮件的发件人:

To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.

为防止欺骗 - Gmail/Outlook.com 不允许您使用任意用户帐户名发送邮件。

If you have a limited number of senders you can follow these instructions and then set the Fromfield to this address: Sending mail from a different address

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

If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :

如果您想从任意电子邮件地址(例如用户输入电子邮件的网站上的反馈表,而您不希望他们直接向您发送电子邮件)发送关于您能做的最好的事情:

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

This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.

这将使您只需在您的电子邮件帐户中点击“回复”即可在反馈页面上回复您乐队的粉丝,但他们不会收到您的实际电子邮件,这可能会导致大量垃圾邮件。

If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).

如果您处于受控环境中,这很好用,但请注意,即使指定了回复地址(我不知道是哪个),我也看到一些电子邮件客户端发送到发件人地址。

回答by RAJESH KUMAR

If you want to send background email, then please do the below

如果您想发送后台电子邮件,请执行以下操作

 public void SendEmail(string address, string subject, string message)
 {
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()
    {

      //Place your Code here 

     });
  threadSendMails.IsBackground = true;
  threadSendMails.Start();
}

and add namespace

并添加命名空间

using System.Threading;

回答by iTURTEV

Here is one method to send mail and getting credentials from web.config:

这是发送邮件和从 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;
    }

}

And the corresponding section in web.config:

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

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

回答by GOPI

Include this,

包括这个,

using System.Net.Mail;

And then,

进而,

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
client.EnableSsl = true;

client.Send(sendmsg);

回答by Premdeep Mohanty

I hope this code will work fine. You can have a try.

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

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

string fromAddress = "[email protected]";
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("[email protected]");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";

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