In this article I will explain with an example, how to send email with attachment from a specific URL in Windows Forms (WinForms) Application 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 App.Config file
The following Mail Server settings need to be saved in the App.Config file.
<configuration>
<appSettings>
<add key="Host" value="smtp.gmail.com" />
<add key="Port" value="587" />
<add key="EnableSsl" value="True" />
<add key="DefaultCredentials" value="True" />
</appSettings>
</configuration>
Form Design
The Form consists of following controls:
TextBox – For capturing the values of Recipient Email address, Subject, Body, Gmail account, email address and Gmail account password.
Button – For sending email.
The Button has been assigned with a Click event handler.
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;
VB.Net
Imports System.IO
Imports System.Net
Imports System.Net.Http
Imports System.Net.Mail
Imports System.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 C# and VB.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 Stream object.
After that, the Recipient email address (toAddress), the Sender email address (fromAddress), Subject, 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 App.Config file and set to the respective properties of SmtpClient class along with the Credentials.
Finally, the email is being sent and the success message is displayed using MessageBox class.
C#
private 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 App.Config.
string host = ConfigurationManager.AppSettings["Host"];
int port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
bool enableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
bool defaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["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);
MessageBox.Show("Email sent.", "Message");
}
}
}
}
}
VB.Net
Private Sub SendEmail(sender As Object, e As EventArgs) Handles btnSend.Click
'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 App.Config.
Dim host As String = ConfigurationManager.AppSettings("Host")
Dim port As Integer = Convert.ToInt32(ConfigurationManager.AppSettings("port"))
Dim enableSsl As Boolean = Convert.ToBoolean(ConfigurationManager.AppSettings("EnableSsl"))
Dim defaultCredentials As Boolean = Convert.ToBoolean(ConfigurationManager.AppSettings("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 SmtpClient = New SmtpClient()
smtp.Host = host
smtp.Port = port
smtp.EnableSsl = enableSsl
smtp.UseDefaultCredentials = defaultCredentials
Dim networkCred As NetworkCredential = New NetworkCredential(txtEmail.Text, txtPassword.Text)
smtp.Credentials = networkCred
smtp.Send(mm)
MessageBox.Show("Email sent.", "Message")
End Using
End Using
End Using
End Using
End Sub
Screenshots
Email Form
Received Email
Downloads