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

C# 通过Gmail在.NET中发送电子邮件,c#,.net,email,smtp,gmail,C#,.net,Email,Smtp,Gmail,我不再依赖我的主机发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。这些电子邮件是给我在节目中扮演的乐队的个性化电子邮件 可以这样做吗?确保使用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

我不再依赖我的主机发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。这些电子邮件是给我在节目中扮演的乐队的个性化电子邮件


可以这样做吗?

确保使用
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);
}

上面的答案行不通。您必须设置
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);
}
这是我的版本:“”


这是发送带有附件的电子邮件。。简洁

资料来源:


来源

下面是使用C#发送邮件的示例工作代码,在下面的示例中,我使用的是google的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);
}

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

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

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

如果您希望从任意电子邮件地址(例如网站上的反馈表,用户在其中输入电子邮件,而您不希望他们直接向您发送电子邮件)发送邮件,您可以做到以下几点:

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
这会让你只需点击你的电子邮件帐户中的“回复”,在反馈页面上回复你乐队的粉丝,但他们不会收到你的实际电子邮件,这可能会导致大量垃圾邮件


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

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

 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;

以下是从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;
    }

}
<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>
public static string sendmail(string To,string Subject,string Msg,bool bodyHtml=false,bool test=false,Stream AttachmentStream=null,string AttachmentType=null,string AttachmentFileName=null)
{
尝试
{
System.Net.Mail.MailMessage newMsg=新系统.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings[“mailCfg”],收件人,主题,Msg);
newMsg.BodyEncoding=System.Text.Encoding.UTF8;
newMsg.HeadersEncoding=System.Text.Encoding.UTF8;
newMsg.SubjectEncoding=System.Text.Encoding.UTF8;
System.Net.Mail.SmtpClient SmtpClient=新系统.Net.Mail.SmtpClient();
if(AttachmentStream!=null&&AttachmentType!=null&&AttachmentFileName!=null)
{
System.Net.Mail.Attachment Attachment=新的System.Net.Mail.Attachment(AttachmentStream,AttachmentFileName);
System.Net.Mime.ContentDisposition=附件.ContentDisposition;
disposition.FileName=附件文件名;
disposition.DispositionType=System.Net.Mime.DispositionTypeNames.Attachment;
newMsg.Attachments.Add(附件);
}
如果(测试)
{
smtpClient.PickupDirectoryLocation=“C:\\TestEmail”;
smtpClient.DeliveryMethod=System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
}
其他的
{
//smtpClient.EnableSsl=true;
}
newMsg.IsBodyHtml=bodyHtml;
smtpClient.Send(newMsg);
返回已发送的\u OK;
}
捕获(例外情况除外)
{
返回“错误:+ex.消息”
+“

内部异常:” +例外情况; } }
以及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;
    }

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

包括这一点

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

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

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

为了让它正常工作,我必须启用我的gmail帐户,使其他应用程序能够访问。这是通过“启用不太安全的应用程序”和使用此链接完成的:
谷歌可能会阻止一些不使用现代安全标准的应用程序或设备的登录尝试。由于这些应用和设备更容易入侵,阻止它们有助于确保您的帐户更安全

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

  • iOS 6或更低版本的iPhone或iPad上的邮件应用程序
  • 8.1版本之前的Windows phone上的邮件应用程序
  • 一些桌面邮件客户端,如Microsoft Outlook和Mozilla Thunderbird
因此,您必须在您的google帐户中启用不太安全的登录

登录google帐户后,转到:




在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);
    }
}
使用(MailMessage=newmailmessage())
{
mail.From=新邮件地址(“email@gmail.com");
mail.To.Add(“somebody@domain.com");
mail.Subject=“你好,世界”;
mail.Body=“你好”;
mail.IsBodyHtml=true;
mail.Attachments.Add(新附件(“C:\\file.zip”);
使用(SmtpClient smtp=newsmtpclient(“smtp.gmail.com”,587))
{
smtp.Credentials=新的网络凭据(“email@gmail.com“,”密码“);
smtp.EnableSsl=true;
smtp.发送(邮件);
}
}

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

如果您已登录(谷歌),您可以按照链接切换“打开”“访问不太安全的应用程序”

使用这种方式

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;

关于wo的其他答案
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();
     }
}
}
}
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)
        { 
          // Write the exception to a Log file.
        }
        catch (SmtpException ex)
        { 
           // Write the exception to a Log file.
        }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}
    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());
        }
    }
    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);
    }