In this article I will explain with an example, how to send email with attachment from a specific URL in ASP.Net using C# and VB.Net.
PDF File URL
The following
PDF file will be used in this article for sending as attachment with email.
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing the values of Recipient Email address, Subject, Body, Gmail account email address, Gmail account password.
Button – For sending email.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 80px">To:</td>
<td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td valign="top">Body:</td>
<td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="150" Width="200"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Email:</td>
<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="SendEmail" /></td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Http
Imports System.Net.Mail
Imports System.Configuration
Imports System.Net.Configuration
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)
Sending email with attachment from URL in ASP.Net
When Send Button is clicked, first the Security Protocol is set.
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 Web.Config file and set to the respective properties of SmtpClient class along with the Credentials.
C#
protected void SendEmail(object sender, EventArgs e)
{
//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 Web.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string host = smtpSection.Network.Host;
int port = smtpSection.Network.Port;
bool enableSsl = smtpSection.Network.EnableSsl;
bool defaultCredentials = smtpSection.Network.DefaultCredentials;
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
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(txtEmail.Text, txtPassword.Text);
smtp.Credentials = networkCred;
smtp.Send(mm);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
}
}
}
}
VB.Net
Protected Sub SendEmail(sender As Object, e As EventArgs)
'Setting TLS 1.2 protocol.
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
Using client As New HttpClient()
'Read the file to Stream from URL.
Dim apiUrl As String = "https://raw.githubusercontent.com/aspsnippets/test/master/Sample.pdf"
Using stream As Stream = client.GetStreamAsync(apiUrl).Result
'Read SMTP section from Web.Config.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Dim host As String = smtpSection.Network.Host
Dim port As Integer = smtpSection.Network.Port
Dim enableSsl As Boolean = smtpSection.Network.EnableSsl
Dim defaultCredentials As Boolean = smtpSection.Network.DefaultCredentials
Using mm As New MailMessage(txtEmail.Text, txtTo.Text)
mm.Subject = txtSubject.Text
mm.Body = txtBody.Text
mm.IsBodyHtml = False
'Attaching file from URL.
mm.Attachments.Add(New Attachment(stream, Path.GetFileName(apiUrl)))
Using smtp As New SmtpClient()
smtp.Host = host
smtp.Port = port
smtp.EnableSsl = enableSsl
smtp.UseDefaultCredentials = defaultCredentials
Dim networkCred As New NetworkCredential(txtEmail.Text, txtPassword.Text)
smtp.Credentials = networkCred
smtp.Send(mm)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Email sent.');", True)
End Using
End Using
End Using
End Using
End Sub
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
Received Email
Downloads