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

时间:2008-08-28 13:28:38

标签: c# .net email smtp gmail

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

24 个答案:

答案 0 :(得分:1018)

请务必使用System.Net.Mail,而不是已弃用的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);
}

答案 1 :(得分:148)

上述答案无效。您必须设置DeliveryMethod = SmtpDeliveryMethod.Network,否则它将返回“客户端未经过身份验证”错误。暂停时间也是个好主意。

修订代码:

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

答案 2 :(得分:86)

其他答案“从服务器”开始在gmail帐户中首先为安全性较低的应用启用访问权限

看起来最近谷歌改变了它的安全政策。评分最高的答案不再有效,直到您按照此处所述更改帐户设置:https://support.google.com/accounts/answer/6010255?hl=en-GB enter image description here

enter image description here

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

答案 3 :(得分:39)

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

来源: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 mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    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 mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

答案 4 :(得分:18)

Google可能阻止某些不使用现代安全标准的应用或设备尝试登录。由于这些应用和设备更易于破解,因此阻止它们有助于保持帐户安全。

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

  • 适用于iOS 6或更低版本的iPhone或iPad上的邮件应用
  • 8.1手机版之前的Windows手机上的邮件应用
  • 某些桌面邮件客户端,如Microsoft Outlook和Mozilla Thunderbird

因此,您必须在Google帐户中启用安全登录

登录Google帐户后,请转到:

https://myaccount.google.com/lesssecureapps

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

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

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("email@gmail.com");
    mail.To.Add("somebody@domain.com");
    mail.Subject = "Hello World";
    mail.Body = "<h1>Hello</h1>";
    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@gmail.com", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}

答案 5 :(得分:15)

这是我的版本:“Send Email In C # Using Gmail”。

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

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

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      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();
     }
    }
   }
 }

答案 6 :(得分:14)

让我开始工作,我必须启用我的Gmail帐户才能让其他应用获得访问权限。这是通过使用此链接“启用安全性较低的应用”和完成的: https://accounts.google.com/b/0/DisplayUnlockCaptcha

答案 7 :(得分:13)

我希望这段代码能正常运行。你可以尝试一下。

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

答案 8 :(得分:8)

包括此,

using System.Net.Mail;

然后,

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("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);

答案 9 :(得分:7)

来源Send email in ASP.NET C#

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

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

public void SendEmail(string address, string subject, string message)
{
    string email = "yrshaikh.mail@gmail.com";
    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);
}

答案 10 :(得分:6)

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

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

      //Place your Code here 

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

并添加名称空间

using System.Threading;

答案 11 :(得分:4)

使用这种方式

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("mail-id@gmail.com","MyPassWord");
client.Send(sendmsg);

别忘了这个:

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

答案 12 :(得分:4)

一个提示! 检查发件人收件箱,也许您需要允许不太安全的应用。 请参阅:https://www.google.com/settings/security/lesssecureapps

答案 13 :(得分:4)

试试这个,

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("your_email_address@gmail.com");
            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());
        }
    }

答案 14 :(得分:3)

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

为防止欺骗,Gmail / Outlook.com不允许您从任意用户帐户名发送。

如果您的发件人人数有限,则可以按照这些说明操作,然后将From字段设置为以下地址:Sending mail from a different address

如果您想要从任意电子邮件地址发送(例如用户输入电子邮件的网站上的反馈表单,而您不希望他们直接通过电子邮件发送给您),那么您可以做的最好的事情是:

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

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

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

答案 15 :(得分:3)

我遇到了同样的问题,但是通过转到gmail的安全设置和允许安全性较低的应用来解决问题。 Domenic&amp; D代码Donny工作,但只有你启用了那个设置

如果您已登录(使用Google),则可以关注this链接并切换“开启”以获取“访问不太安全的应用” < / p>

答案 16 :(得分:3)

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

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

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      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();
     }
}
}
}

答案 17 :(得分:2)

以下是一种从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>

答案 18 :(得分:1)

我遇到的问题是我的密码中有一个黑色的&#34; \&#34; ,我将其复制粘贴而未发现会导致问题。

答案 19 :(得分:1)

another answer复制,上述方法有效,但gmail总是替换&#34;来自&#34;并且&#34;回复&#34;发送电子邮件与实际发送的Gmail帐户。显然有一种解决方法:

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

&#34; 3。在“帐户”标签中,单击链接&#34;添加您拥有的另一个电子邮件地址&#34;然后验证它&#34;

或者可能是this

更新3:读者Derek Bennett说,&#34;解决方案是进入你的Gmail设置:帐户和&#34;默认&#34;您的Gmail帐户以外的帐户。这将导致gmail使用默认帐户的电子邮件地址重新编写“发件人”字段。&#34;

答案 20 :(得分:1)

试试这个

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("abc@gmail.com", "Sender Name"); // abc@gmail.com = 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("abc@gmail.com", "pass")   // abc@gmail.com = 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;
}

答案 21 :(得分:0)

您可以尝试Mailkit。它为您提供更好,更先进的发送邮件功能。您可以从this中找到更多信息,这是一个示例

    MimeMessage message = new MimeMessage();
    message.From.Add(new MailboxAddress("FromName", "YOU_FROM_ADDRESS@gmail.com"));
    message.To.Add(new MailboxAddress("ToName", "YOU_TO_ADDRESS@gmail.com"));
    message.Subject = "MyEmailSubject";

    message.Body = new TextPart("plain")
    {
        Text = @"MyEmailBodyOnlyTextPart"
    };

    using (var client = new SmtpClient())
    {
        client.Connect("SERVER", 25); // 25 is port you can change accordingly

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.
        client.AuthenticationMechanisms.Remove("XOAUTH2");

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");

        client.Send(message);
        client.Disconnect(true);
    }

答案 22 :(得分:0)

为避免Gmail中的安全问题,您应该首先从Gmail设置中生成一个应用密码,即使您使用两步验证,也可以使用此密码代替真实密码来发送电子邮件。

答案 23 :(得分:0)

How to Set App-specific password for gmail

如果您的Google密码不起作用,则可能需要在Google上为Gmail创建应用专用密码。 https://support.google.com/accounts/answer/185833?hl=en