Domanda

Invece di basarsi sul mio host per inviare email, stavo pensando di inviare i messaggi di posta elettronica utilizzando il mio account Gmail.I messaggi di posta elettronica personalizzati e-mail per la band che mi gioco il mio show.È possibile fare?

È stato utile?

Soluzione

Assicurarsi di utilizzare System.Net.Mail, non deprecato System.Web.Mail.Facendo SSL con System.Web.Mail è una grave pasticcio di hacky estensioni.

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

Altri suggerimenti

Sopra non funziona.È necessario impostare DeliveryMethod = SmtpDeliveryMethod.Network o tornerà con un "client non autenticato"errore.Inoltre è sempre una buona idea mettere un timeout.

Codice modificato:

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

Per le altre risposte lavoro "da un server" prima Attivare l'Accesso per meno sicuro apps nell'account gmail.

Sembra recentemente google ha cambiato la politica di sicurezza.Il top rated risposta non funziona più, fino a quando si modifica le impostazioni del tuo account come descritto qui: https://support.google.com/accounts/answer/6010255?hl=en-GBenter image description here

enter image description here

Nel Marzo del 2016, google ha cambiato l'impostazione della posizione di nuovo!

Questo è quello di inviare e-mail con allegato..Semplice e breve..

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

}

Google potrebbe bloccare segno tentativi da alcune applicazioni o dispositivi che non utilizzano moderni standard di sicurezza.Dal momento che questi dispositivi e app sono più facili da rompere in, blocco li aiuta a mantenere il tuo account più sicuro.

Alcuni esempi di applicazioni che non supportano i più recenti standard di sicurezza includono:

  • L'applicazione e-Mail sul vostro iPhone o iPad con iOS 6 o al di sotto
  • L'app Mail di Windows phone che precede la versione 8.1
  • Alcuni Desktop client di posta come Microsoft Outlook e Mozilla Thunderbird

Pertanto, è necessario abilitare Meno Sicuro Di Accesso nel tuo account google.

Dopo il segno nell'account google, vai a:

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

In C#, è possibile utilizzare il codice riportato di seguito:

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

Ecco la mia versione:"Inviare E-Mail In C # Utilizzando 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();
     }
    }
   }
 }

Per me per farlo funzionare ho dovuto abilitare il mio account gmail, rendendo possibile per le altre applicazioni per accedere.Questo viene fatto con l'opzione "abilita meno sicuro apps" e anche utilizza questo link:https://accounts.google.com/b/0/DisplayUnlockCaptcha

Spero che questo codice funziona bene.Si può avere una prova.

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

Includere questo,

using System.Net.Mail;

E poi,

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

Fonte : Invia una email a ASP.NET C#

Qui di seguito è un esempio di codice per l'invio di un messaggio e-mail utilizzando C#, nel seguente esempio sto usando google server smtp.

Il codice è abbastanza auto esplicativo, sostituire l'email e la password con la vostra email e la password di valori.

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

Se si desidera inviare in background e-mail, quindi si prega di fare il seguito

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

      //Place your Code here 

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

e aggiungere spazio dei nomi

using System.Threading;

utilizzare in questo modo

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

Non dimenticate questo :

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

Un Suggerimento!Controlla il mittente di posta in arrivo, forse è necessario consentire a meno di app sicure.Vedere: https://www.google.com/settings/security/lesssecureapps

Prova Questo,

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

La modifica del mittente su Gmail / Outlook.com e-mail:

Per impedire lo spoofing - Gmail/Outlook.com non permette di inviare da un arbitrario nome dell'account utente.

Se si dispone di un numero limitato di mittenti puoi seguire queste istruzioni e quindi impostare il From campo a questo indirizzo: Inviare e-mail da un indirizzo diverso

Se si vuole inviare da un qualsiasi indirizzo di posta elettronica (ad esempio un modulo di feedback sul sito web in cui l'utente inserisce la propria e-mail e non si desidera loro email direttamente) circa il meglio che puoi fare è questo :

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

Questo ti basta premere "rispondi" nel tuo account e-mail di risposta per i fan della band su una pagina di feedback, ma essi non ottenere il vostro e-mail reale, che porterebbe ad una tonnellata di spam.

Se siete in un ambiente controllato, questo funziona alla grande, ma si prega di notare che ho visto in alcuni client di posta elettronica per inviare l'indirizzo del mittente anche quando la risposta è specificato (non so quale).

Ho avuto lo stesso problema, ma si è risolto andando su gmail, impostazioni di sicurezza e Permettendo a Meno di app Sicure.Il Codice da Domenico & Donny funziona, ma solo se è attivata l'impostazione

Se hai effettuato l'accesso (di Google) è possibile seguire questo link e alternare "Accendere" per "L'accesso per meno di app sicure"

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

Ecco un metodo per inviare la posta e ottenere le credenziali dal 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;
    }

}

E la sezione corrispondente nel 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>

Il problema per me è che la mia password avuto un blackslash "\" in esso, che ho copia incollato senza rendersi conto che potrebbe causare problemi.

Provate questo

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

Copia da un'altra risposta, in alto sopra di metodi di lavoro, ma gmail sostituisce sempre il "da" e "rispondi a" e-mail con l'invio effettivo account gmail.a quanto pare c'è un lavoro in giro comunque:

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

"3.Nella Scheda Account, fai Clic sul link "Aggiungi un altro indirizzo email", quindi verificare"

O forse questo

Aggiorna 3:Lettore di Derek Bennett dice, "La soluzione è andare in Impostazioni di gmail:Conti e "imposta come predefinito" con un account diverso dal tuo account gmail.Questo sarà causa di gmail per ri-scrivere il campo Da qualsiasi è l'account predefinito indirizzo di posta elettronica è."

Puoi provare Mailkit.Il suo dare il meglio e anticipo functionlity per inviare la posta.Si può trovare di più da questo Qui è un esempio

    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);
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top