Saturday, November 27, 2021

Send Email with Attachment in .NET Core

 In this article we will discuss how to send emails with attachment in ASP .Net Core using Gmail SMTP.


Default SMTP Settings for Gmail
  • Gmail SMTP server address: smtp.gmail.com.
  • Gmail SMTP username: Your Gmail address (for example, example@gmail.com)
  • Gmail SMTP password: Your Gmail password.
  • Gmail SMTP port (TLS): 587.
  • Gmail SMTP port (SSL): 465.
  • Gmail SMTP TLS/SSL required: Yes.
MailMessage Class Properties (Mailmessage are reference from System.Net.Mail)
  • From – Sender’s email address.
  • To – Recipient(s) Email Address.
  • CC – Carbon Copies (if any).
  • BCC – Blind Carbon Copies (if any).
  • Subject – Subject of the Email.
  • Body – Body of the Email.
  • IsBodyHtml – Specify whether body contains text or HTML mark up.
  • Attachments – Attachments (if any).
  • ReplyTo – ReplyTo Email address.
Let's create a .NET Core web application and see how we integrate the Gmail SMTP. We use Visual Studio 2019 with .NET Core Sdk 3.1

Model
Model class named EmailConfig with the following properties.

public class EmailConfig
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public IFormFile Attachment { get; set; }
}
public class mailConfig
{
public string mailFrom { get; set; }
public string mailpassword { get; set; }
}
view rawEmailConfig.cs hosted with ❤ by GitHub

  • We take EmailConfig class to hold the information of Email. mailConfig class are used to hold the Gmail Credentials in appsettings.json 
  • IFormFile is the new Class for Files in .Net Core. It is a replacement of HttpPostedFileBase class.
{
"MailConfig": {
"mailFrom": "**********@gmail.com",
"mailpassword": "**********"
}
UI
Create a View page like below; the html should like

@model EmailConfig
@{
ViewData["Title"] = "Home Page";
}
<form asp-controller="Home" asp-action="EmailSend" asp-antiforgery="true" enctype="multipart/form-data">
<div class="text-center">
<div class="container">
<div class="row mt-3">
<div class="col-sm-4">
To
</div>
<div class="col-sm-8">
<input type="text" asp-for="To" name="To" class="form-control" />
</div>
</div>
<div class="row mt-3">
<div class="col-sm-4">
Subject
</div>
<div class="col-sm-8">
<input type="text" asp-for="Subject" name="Subject" class="form-control" />
</div>
</div>
<div class="row mt-3">
<div class="col-sm-4">
Body
</div>
<div class="col-sm-8">
<textarea asp-for="Body" name="Body" class="form-control"></textarea>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-4">
Attachment
</div>
<div class="col-sm-8">
<input type="file" asp-for="Attachment" name="Attachment" class="form-control" />
</div>
</div>
<div class="row mt-3">
<div class="col-sm-4">
</div>
<div class="col-sm-8">
<input type="submit" name="Send Email" id="btnSendEmail" class="btn btn-primary" />
</div>
</div>
<div class="clearfix">&nbsp;</div>
</div>
</div>
</form>
view rawIndex.cshtml hosted with ❤ by GitHub
appsettings.json. To access the value in appsettings.json, follow the link how-to-read-values-from-appsettingsjson We need to access the Gmail credentials as through dependency injection like below;
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton(Configuration.GetSection("MailConfig").Get<mailConfig>());
}
view rawStartup.cs hosted with ❤ by GitHub
Controller
Add the Post method in HomeController like below;
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult EmailSend(EmailConfig _email)
{
using (MailMessage mm = new MailMessage(_config.mailFrom, _email.To))
{
mm.Subject = _email.Subject;
mm.Body = _email.Body;
if (_email.Attachment.Length > 0)
{
string fileName = Path.GetFileName(_email.Attachment.FileName);
mm.Attachments.Add(new Attachment(_email.Attachment.OpenReadStream(), fileName));
}
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(_config.mailFrom, _config.mailpassword);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ViewBag.Message = "Email sent.";
}
}
return View("Index");
}

Add caption
Note: If you face the secure connection error for sending email the follow the link smtp-server-requires-secure-connection.html

Finally hit the submit button and the email was sent as expected into the provided gmail account.

</> Find the Source Code in Github.com/CoreProgramm/

   Summary
  In this tutorial we discussed how to Send Email with Attachment in .NET Core using Gmail SMTP. If have any question related to this topic then give your feedback.

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...