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

Sending email in .NET through Gmail

我没有依靠我的主机发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。这些邮件是我在节目中播放的乐队的个性化电子邮件。有可能吗?


一定要使用System.Net.Mail,不要使用不推荐使用的System.Web.Mail。使用System.Web.Mail进行ssl是一堆糟糕的黑客扩展。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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);
}


上面的答案不起作用。您必须设置DeliveryMethod = SmtpDeliveryMethod.Network,否则它将返回一个"客户端未经身份验证"错误。另外,设置一个超时总是一个好主意。

修订规范:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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);
}


对于"从服务器"工作的其他答案,首先打开Gmail帐户中安全性较低的应用程序的访问。

看起来最近谷歌改变了它的安全政策。最高评级的答案将不再有效,除非您按照以下描述更改帐户设置:https://support.google.com/accounts/answer/6010255?hl=en-gbenter image description here

enter image description here

截至2016年3月,谷歌再次更改了设置位置!


这是用附件发送电子邮件。简单而简短……

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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);

}


谷歌可能会阻止一些不使用现代安全标准的应用程序或设备的登录尝试。由于这些应用程序和设备更容易侵入,阻止它们有助于保持您的帐户安全。

一些不支持最新安全标准的应用程序示例包括:

  • iOS 6或更低版本的iPhone或iPad上的邮件应用程序
  • 8.1版本之前Windows Phone上的邮件应用程序
  • 一些桌面邮件客户端,如Microsoft Outlook和Mozilla Thunderbird

因此,您必须在Google帐户中启用安全性较低的登录。

登录Google帐户后,请转到:

https://myaccount.google.com/lessecureapps

https://www.google.com/settings/security/lessecureapps

在C中,您可以使用以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("[email protected]");
    mail.To.Add("[email protected]");
    mail.Subject ="Hello World";
    mail.Body ="Hello";
    mail.IsBodyHtml = true;
    mail.Attachments.Add(new Attachment("C:\\file.zip"));

    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
    {
        smtp.Credentials = new NetworkCredential("[email protected]","password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}

这是我的版本:"使用Gmail用C发送电子邮件"。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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();
     }
    }
   }
 }


为了让它工作,我必须启用我的Gmail帐户,使其他应用程序可以访问。这是通过"启用不太安全的应用程序"以及使用此链接完成的:https://accounts.google.com/b/0/displayUnlockCaptcha


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 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);


包括这个,

1
using System.Net.Mail;

然后,

1
2
3
4
5
6
7
8
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);


来源:用ASP.NET C发送电子邮件#

下面是一个使用c_发送邮件的工作代码示例,在下面的示例中,我使用的是Google的SMTP服务器。

代码非常简单,用您的电子邮件和密码值替换电子邮件和密码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
}


如果您要发送背景电子邮件,请执行以下操作

1
2
3
4
5
6
7
8
9
10
11
12
 public void SendEmail(string address, string subject, string message)
 {
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()
    {

      //Place your Code here

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

并添加命名空间

1
using System.Threading;

用这种方式

1
2
3
4
5
6
7
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("[email protected]","MyPassWord");
client.Send(sendmsg);

别忘了:

1
2
using System.Net;
using System.Net.Mail;

一个小费!检查发件人收件箱,也许您需要允许安全性较低的应用程序。请参阅:https://www.google.com/settings/security/lessecureapps


试试这个,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("[email protected]");
            mail.To.Add("to_address");
            mail.Subject ="Test Mail";
            mail.Body ="This is for testing SMTP mail from GMAIL";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username","password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("mail Send");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }


我也遇到过同样的问题,但通过访问Gmail的安全设置并允许不太安全的应用程序解决了这个问题。Domenic&Donny的代码可以工作,但前提是您启用了该设置。

如果您登录(到谷歌),您可以通过此链接,并在"访问不太安全的应用程序"中切换"打开"。


更改gmail/outlook.com电子邮件中的发件人:

为了防止欺骗-gmail/outlook.com不允许您从任意用户帐户名发送邮件。

如果发件人数量有限,可以按照这些说明进行操作,然后将EDOCX1[4]字段设置为此地址:从其他地址发送邮件

如果您希望从任意电子邮件地址(如用户输入电子邮件的网站上的反馈表,而您不希望他们直接向您发送电子邮件)发送有关您能做到的最佳做法是:

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

这会让你只需点击电子邮件帐户中的"回复"就可以在反馈页面上回复你的粉丝,但他们不会收到你的实际电子邮件,这可能会导致一吨垃圾邮件。

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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();
     }
}
}
}

以下是从web.config发送邮件和获取凭据的一种方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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中的相应部分:

1
2
3
4
5
6
7
8
</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>

对我来说,问题是我的密码中有一个黑斜杠"",我复制粘贴的时候没有意识到它会导致问题。


从另一个答案复制,上述方法有效,但Gmail总是用实际发送的Gmail帐户替换"发件人"和"回复收件人"电子邮件。不过,显然还有一项工作要做:

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

"3。在"帐户"选项卡中,单击"添加您拥有的其他电子邮件地址"链接,然后验证它。

或者可能是这个

更新3:读者DerekBennett说,"解决方案是进入你的Gmail设置:账户,并"默认"一个账户而不是你的Gmail账户。这将导致Gmail使用默认帐户的电子邮件地址重新写入"发件人"字段。"


试试这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("[email protected]","Sender Name"); // [email protected] = input Sender Email Address
        mailMessage.From = mailAddress;
        mailAddress = new MailAddress(receiverEmail, ReceiverName);
        mailMessage.To.Add(mailAddress);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;

        SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
        {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("[email protected]","pass")   // [email protected] = input sender email address  
                                                                           //pass = sender email password
        };

        try
        {
            mailSender.Send(mailMessage);
            return true;
        }
        catch (SmtpFailedRecipientException ex)
        { }
        catch (SmtpException ex)
        { }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}