una servidor segura requiere net enviar desde correos correo conexión con cliente autenticó asp c# .net email smtp gmail

servidor - send email c# smtp gmail



Enviando correo electrónico en.NET a través de Gmail (22)

En lugar de confiar en mi host para enviar correos electrónicos, estaba pensando en enviar los mensajes de correo electrónico usando mi cuenta de Gmail. Los correos electrónicos son correos electrónicos personalizados a las bandas que toco en mi show. Es posible de hacer?


Al copiar de otra respuesta , los métodos anteriores funcionan, pero gmail siempre reemplaza el correo electrónico "de" y "responder a" con la cuenta real de gmail que envía. aparentemente hay un trabajo alrededor sin embargo:

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

"3. En la pestaña Cuentas, haga clic en el enlace" Agregar otra dirección de correo electrónico de su propiedad "luego verifíquela"

O posiblemente this

Actualización 3: el lector Derek Bennett dice: "La solución es ir a la Configuración de gmail: Cuentas y" Establecer como predeterminado "una cuenta que no sea su cuenta de Gmail. Esto hará que Gmail vuelva a escribir el campo De con cualquier correo electrónico de la cuenta predeterminada La dirección es."


Aquí está mi versión: " Enviar correo electrónico en C # usando 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 = "[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(); } } } }


Aquí hay un método para enviar correo y obtener credenciales de 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; } }

Y la sección correspondiente en web.config:

<appSettings> <add key="mailCfg" value="[email protected]"/> </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>


Cambio de remitente en el correo electrónico de Gmail / Outlook.com:

Para evitar la suplantación de identidad: Gmail / Outlook.com no le permitirá enviar desde un nombre de cuenta de usuario arbitrario.

Si tiene un número limitado de remitentes, puede seguir estas instrucciones y luego configurar el campo From a esta dirección: Enviar correo desde una dirección diferente

Si desea enviar desde una dirección de correo electrónico arbitraria (como un formulario de comentarios en el sitio web donde el usuario ingresa su correo electrónico y no quiere que le envíen un correo electrónico directamente) sobre lo mejor que puede hacer es esto:

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

Esto le permitiría simplemente hacer clic en ''responder'' en su cuenta de correo electrónico para responder al fanático de su banda en una página de comentarios, pero no obtendrían su correo electrónico real, lo que probablemente conduciría a una tonelada de correo no deseado.

Si está en un entorno controlado, esto funciona muy bien, pero tenga en cuenta que he visto que algunos clientes de correo electrónico envían a la dirección desde incluso cuando se especifica la respuesta (no sé cuál).


El problema para mí fue que mi contraseña tenía una barra negra "/" , que copié pegada sin darme cuenta de que causaría problemas.


Espero que este código funcione bien. Puedes tener una oportunidad.

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


Esto es para enviar correo electrónico con archivo adjunto. Simple y corto.

fuente: 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 [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); }


Google puede bloquear los intentos de inicio de sesión de algunas aplicaciones o dispositivos que no utilizan los estándares de seguridad modernos. Dado que estas aplicaciones y dispositivos son más fáciles de abrir, bloquearlos ayuda a mantener su cuenta más segura.

Algunos ejemplos de aplicaciones que no son compatibles con los últimos estándares de seguridad incluyen:

  • La aplicación Mail en tu iPhone o iPad con iOS 6 o inferior
  • La aplicación Mail en su teléfono Windows anterior a la versión 8.1
  • Algunos clientes de correo de escritorio como Microsoft Outlook y Mozilla Thunderbird

Por lo tanto, debe habilitar un inicio de sesión menos seguro en su cuenta de Google.

Después de iniciar sesión en la cuenta de Google, vaya a:

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

En C #, puedes usar el siguiente código:

using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); 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 protected]", "password"); smtp.EnableSsl = true; smtp.Send(mail); } }


Incluye esto,

using System.Net.Mail;

Y entonces,

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


La respuesta anterior no funciona. Tiene que configurar DeliveryMethod = SmtpDeliveryMethod.Network o volverá con un error "el cliente no se autenticó ". También siempre es una buena idea poner un tiempo de espera.

Código revisado:

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



Para que las otras respuestas funcionen "desde un servidor", active Activar el acceso para aplicaciones menos seguras en la cuenta de gmail.

Parece que recientemente Google cambió su política de seguridad. La respuesta mejor calificada ya no funciona, hasta que cambie la configuración de su cuenta como se describe aquí: https://support.google.com/accounts/answer/6010255?hl=en-GB

A partir de marzo de 2016, Google cambió la ubicación de configuración de nuevo!


Prueba este

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


Prueba esto,

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


Si desea enviar un correo electrónico de fondo, haga lo siguiente

public void SendEmail(string address, string subject, string message) { Thread threadSendMails; threadSendMails = new Thread(delegate() { //Place your Code here }); threadSendMails.IsBackground = true; threadSendMails.Start(); }

y agregar espacio de nombres

using System.Threading;


Tuve el mismo problema, pero se resolvió accediendo a la configuración de seguridad de gmail y Permitiendo aplicaciones menos seguras . El Código de Domenic & Donny funciona, pero solo si habilitas esa configuración

Si ha iniciado sesión (en Google), puede seguir https://www.google.com/settings/security/lesssecureapps enlace y activar "Activar" para "Acceso para aplicaciones menos seguras"



usa de esta manera

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

No olvides esto:

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


http://www.systemnetmail.com/ es probablemente el sitio más absurdamente completo dedicado a un solo espacio de nombres .NET ... pero tiene TODO lo que podría desear saber sobre el envío de correo a través de .NET, ya sea ASP.NET o Escritorio.

http://www.systemwebmail.com/ fue la URL original en la publicación, pero no debe usarse para .NET 2.0 y superior.


Fuente : Enviar correo electrónico en ASP.NET C #

A continuación se muestra un ejemplo de código de trabajo para enviar un correo usando C #, en el siguiente ejemplo, estoy usando el servidor smtp de google.

El código se explica por sí mismo, reemplaza el correo electrónico y la contraseña con los valores de tu correo electrónico y contraseña.

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


Asegúrese de usar System.Net.Mail , no el System.Web.Mail desuso. Hacer SSL con System.Web.Mail es un gran desorden de extensiones hacky.

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


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