Envoyer un courriel in.NET par Gmail

au lieu de compter sur mon hôte pour envoyer des e-mails, je pensais envoyer les e-mails en utilisant mon compte Gmail. Les emails sont des emails personnalisés pour les groupes que je joue dans mon émission. Est-il possible de le faire?

770
demandé sur Sameer 2008-08-28 17:28:38

22 réponses

assurez-vous d'utiliser System.Net.Mail , et non System.Web.Mail . Faire SSL avec System.Web.Mail est un gâchis énorme d'extensions hacky.

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);
}
970
répondu Domenic 2014-08-16 09:49:27

La réponse ci-dessus ne fonctionne pas. Vous devez définir DeliveryMethod = SmtpDeliveryMethod.Network ou il reviendra avec un " le client n'a pas été authentifié " erreur. Aussi, il est toujours une bonne idée de mettre un timeout.

Code révisé:

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);
}
140
répondu Donny V. 2013-05-08 04:16:17

Pour les autres réponses à travailler "à partir d'un serveur" première Activer l'Accès pour les moins sécurisés apps dans le compte gmail.

on dirait que google a récemment changé sa politique de sécurité. La réponse la mieux notée ne fonctionne plus, jusqu'à ce que vous changiez les paramètres de votre compte comme décrit ici: https://support.google.com/accounts/answer/6010255?hl=en-GB enter image description here

enter image description here

a partir de mars 2016, google a de nouveau modifié le paramètre!

74
répondu BCS Software 2018-03-22 13:03:02

http://www.systemnetmail.com / est probablement le site le plus complet dédié à un single .NET...mais il a tout ce que vous pouvez toujours vouloir savoir sur l'envoi de courrier via .NET, que ce soit ASP.NET ou de bureau.

http://www.systemwebmail.com / était L'URL d'origine dans le post, mais ne devrait pas être utilisé pour .NET 2.0 et au-dessus.

65
répondu Adam Haile 2013-06-17 16:11:01

il s'agit d'envoyer un e-mail avec pièce jointe.. Simple et court..

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

}
39
répondu Ranadheer Reddy 2013-07-29 13:10:20

Google peut bloquer la connexion de certaines applications ou appareils qui n'utilisent pas les normes de sécurité modernes. Étant donné que ces applications et appareils sont plus faciles à pirater, leur blocage contribue à assurer la sécurité de votre compte.

voici quelques exemples d'applications qui ne prennent pas en charge les dernières normes de sécurité:

  • l'application Mail sur votre iPhone ou iPad avec iOS 6 ou moins

  • l'application de courrier sur votre Windows phone précédant la version 8.1

  • Certains clients de messagerie de Bureau comme Microsoft Outlook et Mozilla Thunderbird

par conséquent, vous devez activer moins sécurisé de connexion dans votre compte google.

après vous être connecté à google account, allez à:

https://myaccount.google.com/lesssecureapps

ou

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

dans C#, vous pouvez utiliser le code suivant:

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);
    }
}
17
répondu mjb 2017-09-13 02:40:14

voici ma version: " envoyer un e-mail en C # en utilisant 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();
     }
    }
   }
 }
15
répondu tehie 2016-07-28 08:43:17

pour que cela fonctionne, j'ai dû activer mon compte gmail pour permettre à d'autres applications d'y accéder. Ceci est fait avec "activer les applications moins sûres" et aussi en utilisant ce lien: https://accounts.google.com/b/0/DisplayUnlockCaptcha

14
répondu Mark Homans 2018-03-22 13:04:56

j'espère que ce code fonctionnera. Vous pouvez avoir un essai.

// 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);
13
répondu Premdeep Mohanty 2014-08-16 09:56:59

Inclure cet,

using System.Net.Mail;

et puis,

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);
8
répondu GOPI 2014-08-16 09:59:29

Source : envoyer un courriel à ASP.NET C#

ci-dessous est un exemple de code de travail pour envoyer un courrier en utilisant C#, dans l'exemple ci-dessous, j'utilise le serveur smtp de google.

le code est assez explicite, remplacez le courriel et le mot de passe par vos valeurs de courriel et de mot de passe.

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);
}
7
répondu Yasser 2012-08-22 12:29:57

si vous souhaitez envoyer un email de fond, alors s'il vous plaît faire le ci-dessous""

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

      //Place your Code here 

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

et ajouter namespace

using System.Threading;
6
répondu RAJESH KUMAR 2013-10-03 18:03:31

utiliser cette voie

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

N'oubliez pas ceci:

using System.Net;
using System.Net.Mail;
4
répondu alireza amini 2015-07-09 06:57:43

Un Conseil! Vérifiez la boîte de réception de l'expéditeur, peut-être que vous avez besoin d'autoriser des applications moins sûres. Voir: https://www.google.com/settings/security/lesssecureapps

4
répondu Gustavo Rossi Muller 2015-07-21 18:53:56

Essayez Cette,

    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());
        }
    }
4
répondu Trimantra Software Solution 2017-01-31 08:23:05

changement d'Expéditeur sur Gmail / Outlook.com email:

pour prévenir la mystification - Gmail/Outlook.com ne vous laissera pas envoyer à partir d'un nom d'utilisateur arbitraire.

si vous avez un nombre limité d'expéditeurs, vous pouvez suivre ces instructions et ensuite définir le champ From à cette adresse: envoyer le courrier à partir d'une adresse différente

si vous souhaitez envoyer à partir d'une adresse e-mail arbitraire (telle que formulaire de commentaires sur le site Web où l'utilisateur entre son courriel et vous ne voulez pas qu'ils vous envoyer directement) sur le mieux que vous pouvez faire est la suivante:

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

cela vous permettrait juste de cliquer sur "Répondre" dans votre compte email pour répondre au ventilateur de votre groupe sur une page de commentaires, mais ils ne recevraient pas votre email réel qui mènerait probablement à une tonne de spam.

si vous êtes dans un environnement contrôlé cela fonctionne bien, mais s'il vous plaît noter que j'ai vu certains les clients envoient un e-mail à l'adresse de from même lorsque la réponse-to est spécifiée (Je ne sais pas laquelle).

3
répondu Simon_Weaver 2013-07-07 20:49:44

j'ai eu le même problème, mais il a été résolu en allant aux paramètres de sécurité de gmail et permettant des applications moins sécurisées . Le Code de Domenic & Donny fonctionne, mais seulement si vous avez activé ce paramètre

si vous êtes connecté (à Google), vous pouvez suivre ce lien et bascule "allumer " pour "accès pour les applications moins sûres"

3
répondu DarkPh03n1X 2015-06-25 07:09:18
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();
     }
}
}
}
3
répondu Moin Shirazi 2015-10-10 13:57:35

Voici une méthode pour envoyer du courrier et obtenir des justificatifs d'identité à partir du 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;
    }

}

et la section correspondante dans 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>
2
répondu iTURTEV 2013-10-08 06:10:55

le problème pour moi était que mon mot de passe avait un blackslash" \ " dans lui, que je recopie collé sans réaliser qu'il causerait des problèmes.

1
répondu Satbir Kira 2015-06-15 11:34:40

Essayer celui-ci

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;
}
1
répondu reza.cse08 2016-02-27 12:40:41

Copying from another answer , les méthodes ci-dessus fonctionnent mais gmail remplace toujours le" de "et la" réponse à " e-mail avec l'envoi compte gmail réelle. apparemment, Il ya un travail autour cependant:

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

" 3. Dans L'onglet Comptes, cliquez sur le lien "ajouter une autre adresse e-mail que vous possédez" puis vérifiez"

ou éventuellement ce

mise à jour 3: le lecteur Derek Bennett dit, "la solution est d'aller dans vos paramètres gmail:comptes et "faire défaut" un compte autre que votre compte gmail. Cela va amener gmail à réécrire le champ From avec quelle que soit l'adresse email du compte par défaut."

1
répondu rogerdpack 2018-03-22 13:07:55