Skip to content

Instantly share code, notes, and snippets.

@miguelcperez
Last active February 14, 2024 13:26
Show Gist options
  • Save miguelcperez/e617dabe0107959cbc4423a9b679f860 to your computer and use it in GitHub Desktop.
Save miguelcperez/e617dabe0107959cbc4423a9b679f860 to your computer and use it in GitHub Desktop.
Envío de correo electrónico ejecutado en segundo plano - C# .Net
using (StreamReader reader = new StreamReader(Server.MapPath("~/Views/Shared/Correo.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{usuario}", usuario); // reemplazar valores en el correo (Correo.html)
var message = new MailMessage();
message.To.Add(new MailAddress("contacto@mail.com"));// correo destino // message.To -> destinatarios visibles entre ellos | message.Bcc -> destinatarios no visibles entre ellos
message.From = new MailAddress("admin@mail.com", "Administrador de Sistemas"); // Remitente del mensaje
message.Subject = "Asunto del mensaje";
message.Body = body; // String body -> código HTML
message.IsBodyHtml = true;
/**************************************HILO DE ENVIO DEL MENSAJE*****************************************************/
Thread email = new Thread(delegate()
{
using (var smtp = new SmtpClient()) // Instancia smtp para el envío del correo
{
try
{
smtp.Send(message); // message -> obj message - clase MailMessage
// Código después del envío del mensaje correcto
}
catch (Exception ex)
{
Console.WriteLine("Falló al enviar mensaje");
Console.WriteLine(ex.Message);
}
}
});
email.IsBackground = true; // para que se ejecute en segundo plano
email.Start(); // para que empiece la ejecución
/*******************************************CONFIGURACION WEB.CONFIG**************************************************/
<system.net>
<mailSettings>
<smtp from="admin@mail.com">
<network host="smtp.mail.com"
port="587"
userName="admin@mail.com"
password="123456"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment