In this article I will explain with an example, how to send email with attachment from a specific URL in ASP.Net Core (.Net Core) MVC .
Note: For beginners in ASP.Net Core (.Net Core 7), please refer my article ASP.Net Core 7: Hello World Tutorial with Sample Program example.
 
 

PDF File URL

The following PDF file will be used in this article for sending as attachment with email.
Send email with attachment from a specific URL in ASP.Net
 
 

Mail Server Settings in AppSettings.json file

The Mail Server settings are saved in the SMTP section as shown below.
{
 "Smtp": {
    "Server""smtp.gmail.com",
    "Port": 587,
    "EnableSsl": true,
    "DefaultCredentials": false
 }
}
 
 

Sending email with attachment from URL

MailMessage class properties

Following are the required properties of the MailMessage class.
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.
 

SmtpClient class methods

Following are the methods of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
Port – Port Number of the SMTP sever (Gmail: 587)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
 
 

Model

The Model class consists of following properties.
public class EmailModel
{
    public string To { getset; }
    public string Subject { getset; }
    public string Body { getset; }
    public string Email { getset; }
    public string Password { getset; }   
}
 
 

Namespaces

You will need to import the following namespaces.
using System.Net;
using System.Net.Mail;
 
 

Controller

The Controller consists of the following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

This Action method accepts EmailModel class as a parameter.
This Action method gets called, the Security Protocol is set.
Note: For previous .Net Framework versions, please refer Using TLS1.2 in .Net 2.0, .Net 3.0, .Net 3.5 and .Net 4.0.
 
Then, the GET request is made using GetStreamAsync method of HttpClient class and the response is stored in a Stream class object.  
After that, the Recipient email address (toAddress), the Sender email address (fromAddress), Subject and Body values are fetched from their respective fields and are set into an object of the MailMessage class.

Setting Body of Email

The Body of the email is Text (Non HTML) hence the IsBodyHtml property of MailMessage class is set to FALSE.

Attaching File

The Stream class object is passed as parameter to new object of Attachment class along with the file name which is ultimately assigned to the MailMessage class object.

Sending Email

Then, an object of the SmtpClient class is created and the values of Host, Port, EnableSsl and UseDefaultCredentials are fetched from the SMTP section of the AppSettings.json file and set to the respective properties of SmtpClient class along with the Credentials.
Finally, the email is being sent and success message is set into a ViewBag object and the View is returned.
C#
public class HomeController : Controller
{
    public IConfiguration Configuration { get; set; }
 
    public HomeController(IConfiguration _configuration)
    {
        this.Configuration = _configuration;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(EmailModel model)
    {
        //Setting TLS 1.2 protocol.
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        using (HttpClient client = new HttpClient())
        {
            string apiUrl = "https://raw.githubusercontent.com/aspsnippets/test/master/Sample.pdf";
 
            //Read the file to Stream from URL.
            using (Stream stream = client.GetStreamAsync(apiUrl).Result)
            {
                //Read SMTP section from AppSettings.json.
                string host = this.Configuration.GetValue<string>("Smtp:Server");
                int port = this.Configuration.GetValue<int>("Smtp:Port");
                bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
                bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
 
                using (MailMessage mm = new MailMessage(model.Email, model.To))
                {
                    mm.Subject = model.Subject;
                    mm.Body = model.Body;
                    mm.IsBodyHtml = false;
 
                    //Attaching file from URL.
                    mm.Attachments.Add(new Attachment(stream, Path.GetFileName(apiUrl)));
                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.Host = host;
                        smtp.Port = port;
                        smtp.EnableSsl = enableSsl;
                        smtp.UseDefaultCredentials = defaultCredentials;
                        NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
                        smtp.Credentials = networkCred;
                        smtp.Send(mm);
                    }
                }
                ViewBag.Message = "Email sent.";
            }
        }
        return View();
    }
}
 
 

View

HTML Markup

Inside the View, in the very first line the EmailModel class is declared as model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of HTML TextBox, TextArea element and a Submit Button.
 

Submitting the Form

When the Submit Button is clicked, the ViewBag object is checked for NULL and if it is not NULL then the value of the object is displayed using JavaScript Alert Message Box.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Email_Attachment_URL_Core.Models.EmailModel
@{
      Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
      <meta name="viewport" content="width=device-width" />
      <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Index" enctype="multipart/form-data">
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td style="width: 80px">To:</td>
                <td><input type="text" asp-for="To" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Subject:</td>
                <td><input type="text" asp-for="Subject" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td valign="top">Body:</td>
                <td><textarea cols="20" rows="3" asp-for="Body"></textarea></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Email:</td>
                <td><input type="text" asp-for="Email" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td>Gmail Password:</td>
                <td><input type="password" asp-for="Password" /></td>
            </tr>
            <tr><td>&nbsp;</td></tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Send" /></td>
            </tr>
        </table>
    </form>
    @if (ViewBag.Message != null)
    {
       <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
       </script>
    }
</body>
</html>
 
 

Possible Errors

The following error occurs when you try to send email using Gmail credentials in your application.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
 

Solution

 
 

Screenshots

Email Form

ASP.Net Core: Send email with attachment from a specific URL
 

Received Email

ASP.Net Core: Send email with attachment from a specific URL
 
 

Downloads