Send email using ASP.NET
I would like to know how to send an email using ASP.NET. the idea will be to click on a button called Send and send a [email protected] (personal) to [email protected] (business). Thanks.
3
Author: Nelson Soares, 2016-04-11
2 answers
Follows an example with asp.net mvc4 and javascript:
MVC:
public ActionResult SendEmail()
{
var fromAddress = new System.Net.Mail.MailAddress("[email protected]", "From Name");
var toAddress = new System.Net.Mail.MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new System.Net.Mail.SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new System.Net.Mail.MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
return View("Index");
}
HTML:
<a href="javascript:;" class="btn btn-primary" id="enviar">Enviar</a>
Javascript:
<script type="text/javascript">
$("#enviar").click(function () {
$.ajax({
url: '@Url.Action("SendEmail", "Home")',
type: 'POST',
data: { },
success: function (result) {
alert('Um email foi enviado com sucesso');
}
});
});
</script>
1
Author: Tiago S, 2016-04-12 00:54:08
Doing it differently, but with the same methods as @Spectron's response, would look like this:
public ActionResult EnviarEmail(){
using (var smtp = new SmtpClient())
{
var message = new MailMessage();
message.To.Add(new MailAddress("[email protected]"));
message.From = new MailAddress("[email protected] ");
message.Subject = "Assunto";
message.Body = "Seu Texto Aqui";
message.IsBodyHtml = true;
var credential = new NetworkCredential
{
UserName = "[email protected]",
Password = "Senha do E-mail aqui"
};
smtp.Credentials = credential;
smtp.Host = "HOST aqui (ex: smtp.google.com)";
smtp.Port = 587; //(Porta aqui)
smtp.EnableSsl = true; //(SSL Enable)
smtp.Send(message);//Enviar mensagem
}
}
return View();
}
However, I advise you to use the Postal.MVC to perform the submission. in this link has an example of the author of the project how to implement, just download the project.
0
Author: Randrade, 2016-04-12 12:12:15