In this article I will explain with an example, how to embed image using
MailKit library in ASP.Net WebForms using C# and VB.Net.
Installing MailKit package from Nuget
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" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
userName="sender@gmail.com"
password="GMAILor2STEP-PASSWORD" />
</smtp>
</mailSettings>
</system.net>
HTML Markup
The HTML Markup consists of following control:
Button – For sending email.
The Button has been assigned with an OnClick event handler.
<asp:Button Text="Send" OnClick="SendEmail" runat="server" />
Namespaces
You will need to import the following namespaces.
C#
using MimeKit;
using MailKit.Net.Smtp;
using MimeKit.Utils;
using MimeKit.Security;
using System.Configuration;
using System.Net.Configuration;
VB.Net
Imports MimeKit
Imports MailKit.Net.Smtp
Imports MimeKit.Utils
Imports MimeKit.Security
Imports System.Configuration
Imports System.Net.Configuration
Embed images using MailKit
MimeMessage Class Properties
Following are the required properties of the MimeMessage 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.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SmtpClient Class Methods
Following are the methods of the SmtpClient class.
Connect – The connection to the SMTP Server is established using the domain and the port number.
Authenticate – The username and password of the SMTP Server is authenticated.
Send – The MimeMessage object is passed to it and the email is sent.
Disconnect – Disconnects the connection with SMTP Server.
Embedding Image using MailKit
When the SendEmail Button is clicked, the Recipient email address (to), the Sender email address (from), Subject and Body are fetched from their respective fields and SMTP section of the Web.Config file and are set into the respective properties of the object of the MimeMessage class.
Setting Body of Email
For Body and LinkedResources, an object of Builder class is created.
Embedding Image
The image file is added to the local variable of MimeEntity class using LinkedResources property of the Builder class.
And, the ContentId of the image is generated using GenerateMessageId method of MimeUtils class.
The Body of the email is HTML (Non Text) hence it is set into the HtmlBody property of the Builder class object.
The HtmlBody of the email is created inside which the ContentId is set to the src property of the Image control and set into an object of MimeMessage class.
Sending Email
Then, an object of SmtpClient is created and the values of Host and Port fetched from the SMTP section of the Web.Config file and are passed as parameter to the Connect method along with the SecureSocketOptions set to Auto.
Note: Setting
Auto allows
MailKit service to decide which
SSL or
TLS option to use. Hence, enabling
SSL is not required.
Also, the CheckCertificateRevocation is set to FALSE.
Note: This is optional and must be used only when Certificate errors are occurring.
Finally, the methods of the Mail Server such as
Connect,
Authenticate,
Send and
Disconnect are executed and a success message is displayed in
JavaScript Alert
MessageBox using
RegisterStartupScript method.
C#
protected void SendEmail(object sender, EventArgs e)
{
//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;
string userName = smtpSection.Network.UserName;
string password = smtpSection.Network.Password;
using (MimeMessage mm = new MimeMessage())
{
mm.From.Add(new MailboxAddress("Sender", smtpSection.From));
mm.To.Add(new MailboxAddress("Recepient", "recepient@gmail.com"));
mm.Subject = "Like ASPSnippets";
BodyBuilder builder = new BodyBuilder();
MimeEntitymimeEntity = builder.LinkedResources.Add(@"D:\Images\Logo_Img.png");
mimeEntity.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = string.Format(@"<img src=""cid:{0}"" /><br /><div style=""border-top:3px solid #61028d""> </div><p>I like ASPSnippets as it provides details code explanation, working samples and great demos.</p>", mimeEntity.ContentId);
mm.Body = builder.ToMessageBody();
using (SmtpClient smtp = new SmtpClient())
{
//Set to False to avoid Certificate verification.
smtp.CheckCertificateRevocation = false;
smtp.Connect(host, port, SecureSocketOptions.Auto);
smtp.Authenticate(userName, password);
smtp.Send(mm);
smtp.Disconnect(true);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
VB.Net
Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
'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 userName As String = smtpSection.Network.UserName
Dim password As String = smtpSection.Network.Password
Using mm As MimeMessage = New MimeMessage()
mm.From.Add(New MailboxAddress("Sender", smtpSection.From))
mm.[To].Add(New MailboxAddress("Recepient", "recepient@gmail.com"))
mm.Subject = "Like ASPSnippets"
Dim builder As BodyBuilder = New BodyBuilder()
Dim mimeEntity As MimeEntity = builder.LinkedResources.Add("D:\Images\Logo_Img.png")
mimeEntity.ContentId = MimeUtils.GenerateMessageId()
builder.HtmlBody = String.Format("<img src=""cid:{0}"" /><br /><div style=""border-top:3px solid #61028d""> </div><p>I like ASPSnippets as it provides details code explanation, working samples and great demos.</p>", mimeEntity.ContentId)
mm.Body = builder.ToMessageBody()
Using smtp As SmtpClient = New SmtpClient()
'Set to False to avoid Certificate verification.
smtp.CheckCertificateRevocation = False
smtp.Connect(host, port, SecureSocketOptions.Auto)
smtp.Authenticate(userName, password)
smtp.Send(mm)
smtp.Disconnect(True)
End Using
End Using
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Email sent.');", True)
End Sub
Possible Errors
The possible errors (exceptions) occurring while sending email with
MailKit in .Net are covered in the following article.
Screenshot
Downloads