Mediante este artÃculo aprenderás paso por paso cuál es la mejor manera de enviar un email utilizando System.Net.Mail. Esto les será muy útil a todos aquellos que estén comenzando con lo báscio de C#, ASP.NET MVC, jQuery y Javascript.
Lo primero que necesitamos saber es cómo obtener los parámetros del servidor SMTP. Los siguientes enlaces te ayudarán a encontrarlos:
Ejemplos de configuración SMTP:
- Office365: Dirección: smtp.office365.com, Puerto: 587, SSL: true
- Gmail: Dirección: smtp.gmail.com, Puerto: 587, SSL: true
- Yahoo: Dirección: smtp.mail.yahoo.com, Puerto: 587, SSL: true
Código del lado del servidor
Clase ConfigurationSMTP
public class ConfigurationSMTP
{
//SMTP parameters
public static string smtpAdress = "smtp.mail.yahoo.com";
public static int portNumber = 587;
public static bool enableSSL = true;
//need it for the secured connection
public static string from = "sender email";
public static string password = "password of the above email";
}
Método SendNewMessage
Este método contiene el código principal que envÃa un nuevo mensaje a una dirección de correo electrónico especÃfica.
Cómo funciona:
- Construimos el mensaje (utilizando la clase MailMessage()) gracias a los datos recibidos desde la solicitud HTTP como: 'Email de destino (Destination Email)', 'Asunto (Subject)', 'Cuerpo del Mensaje (Message Body)'.
- Creamos y configuramos el cliente SMTP utilizando la clase SmtpClient().
- Adjuntamos un parámetro de credenciales cuando intentemos crear la conexión SMTP (utilizando el método smtp.Credentials).
- Enviamos el mensaje.
[HttpPost]
public ActionResult SendNewMessage()
{
try
{
Response.StatusCode = 200;
//getting useful configuration
string smtpAddress = ConfigurationSMTP.smtpAdress;
//it can be a "smtp.office365.com" or whatever,
//it depends on smtp server of your sender email.
int portNumber = ConfigurationSMTP.portNumber; //Smtp port
bool enableSSL = ConfigurationSMTP.enableSSL; //SSL enable
string emailTo = Request.Params["to"];
string subject = Request.Params["subject"];
StringBuilder body = new StringBuilder();
//building the body of our email
body.Append("<html><head> </head><body>");
body.Append("<div style=' font-family: Arial;
font-size: 14px; color: black;'>Hi,<br><br>");
body.Append(Request.Params["message"]);
body.Append("</div><br>");
//Mail signature
body.Append(string.Format("<span style='font-size:11px;font-family:
Arial;color:#40411E;'>{0} - {1} {2}</span><br>",
MessageModel.adress, MessageModel.zip, MessageModel.city));
body.Append(string.Format("<span style='font-size:11px;font-family:
Arial;color:#40411E;'>Mail: <a href="mailto:{0}">{0}</a>
</span><br>", ConfigurationSMTP.from));
body.Append(string.Format("<span style='font-size:11px;font-family:
Arial;color:#40411E;'>Tel: {0}</span><br>",
MessageModel.phone));
body.Append(string.Format("<span style='font-size:11px;font-family:
Arial;'><a href="web site">{0}</a>
</span><br><br>", MessageModel.link));
body.Append(string.Format("<span style='font-size:11px; font-family:
Arial;color:#40411E;'>{0}</span><br>", MessageModel.details));
body.Append( "</body></html>");
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(ConfigurationSMTP.from);
//destination adress
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body.ToString();
//set to true, to specify that we are sending html text.
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
string localFileName = "~/Content/TestAttachement.txt";
//to send a file in attachment.
mail.Attachments.Add(new Attachment
(Server.MapPath(localFileName), "application/pdf"));
//Specify the smtp Server and port number to create a new instance of SmtpClient.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
//passing the credentials for authentication
smtp.Credentials = new NetworkCredential
(ConfigurationSMTP.from, ConfigurationSMTP.password);
//Authentication required
smtp.EnableSsl = enableSSL;
//sending email.
smtp.Send(mail);
}
}
}
catch (Exception ex)
{
//Error response
Response.StatusCode = 400;
}
return null;
}
Código del lado del cliente
index.cshtml
Este archivo contiene dos secciones:
- Código HTML y CSS: Lo utilizaremos para crear y diseñar los campos y controles del formulario
- Código JavaScript: Lo utilizaremos para capturar el evento onsubmit del formulario de contacto y realizar la petición HTTP que invoque el método SendNewMessage
<script type="text/javascript">
$(document).ready(function () {
$("#idFormContact").on("submit", function (e) {
e.preventDefault();
//call external service
var url = "/Home/SendNewMessage";
var formdata = (window.FormData) ? new FormData(this) : null;
var fdata = (formdata !== null) ? formdata : $form.serialize();
$("#idSubmitMvt").attr("disabled", true);
$("#idNotifSuccess").hide();
$("#idNotifError").hide();
//get authorization keys.
$.ajax({
type: "POST",
url: url,
data: fdata,
processData: false,
contentType: false,
success: function (data) {
$("#idNotifSuccess").show();
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error");
$("#idNotifError").show();
}
});
});
});
</script>
Resultado
Fuente: Onasri 12202787
