Advertisements

Send Email Using ASP.NET Core 1.1 With MailKit In Visual Studio 2017


Introduction

We are familiar with Sending Email Using Asp.Net With C#. But today, we are going to teach you how to send email using ASP.NET Core 1.1 with MailKit. We can implement it in ASP.Net Core very easily as compared to the previous versions of ASP.NET.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

MailKit

MailKit is a cross-platform mail client library built on top of MimeKit. That means we get all the mail sending libraries from MailKit, such as – Simple Mail Transfer Protocol (SMTP) etc.

Simple Mail Transfer Protocol (SMTP)

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another.The messages can then be retrieved with an e-mail client using either POP or IMAP.

The following is a list of SMTP Server and Port Numbers.

Sl.No Mail Server SMTP Server( Host ) Port Number
1 Gmail smtp.gmail.com 587
2 Outlook smtp.live.com 587
3 Yahoo Mail smtp.mail.yahoo.com 465
4 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465
5 Hotmail smtp.live.com 465
6 Office365.com smtp.office365.com 587
7 zoho Mail smtp.zoho.com 465

Assemblies Required

The following assemblies are required for sending email using ASP.NET Core with MailKit.

using MailKit.Net.Smtp;
using MimeKit;

Adding MailKit in Our Project

Go to “Tools -> NuGet Package Manager -> Manage Nuget Package for Solutions…” Then, search “MailKit”, Choose and Install the latest version “V1.12.0” in your application.

MailKit Installation

MailKit Installation

Project Structure

New .NET Core tooling is available in Visual Studio 2017 by default. In the Dependencies folder, every package tool has separate folder like MailKit saved into NuGet folder. If you have a client side tool like bower, then its dependencies are saved into it’s folder.

Project Structure ASP.NET Core 1.1

Project Structure ASP.NET Core 1.1

Code

The following code contains the mail sending code of ASP.NET Core.

using MailKit.Net.Smtp;
using MimeKit;
using System;

namespace EmailApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //From Address
                string FromAddress = "From Email Address";
                string FromAdressTitle = "Email from ASP.NET Core 1.1";
                //To Address
                string ToAddress = "To Email Address";
                string ToAdressTitle = "Microsoft ASP.NET Core";
                string Subject = "Hello World - Sending email using ASP.NET Core 1.1";
                string BodyContent = "ASP.NET Core was previously called ASP.NET 5. It was renamed in January 2016. It supports cross-platform frameworks ( Windows, Linux, Mac ) for building modern cloud-based internet-connected applications like IOT, web apps, and mobile back-end.";

                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Subject = Subject;
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = BodyContent

                };

                using (var client = new SmtpClient())
                {

                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    // Note: only needed if the SMTP server requires authentication
                    // Error 5.5.1 Authentication 
                    client.Authenticate("From Address Email", "Password");
                    client.Send(mimeMessage);
                    Console.WriteLine("The mail has been sent successfully !!");
                    Console.ReadLine();
                    client.Disconnect(true);

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

Important Points

  • When you are sending mail with your “gmail” account, enable less secure apps so that you will be able to login from all apps. Otherwise, it will throw authentication error like 5.5.1 authentication.
  • Remove 2-Step Verification.

In the following code, we can mention username for “gmail” account but in other service like “hotmail”, we must provide the full email address because other Microsoft accounts, like Outlook, live, etc. have the same SMTP Server Address “smtp.live.com”.

client.Authenticate("From Address Email", "Password");

csproj

In previous version, ASP.NET Core 1.0 contained all the versions & dependencies in project.json file but in new version, i.e., ASP.NET Core 1.1, they are saved in csproj.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MailKit" Version="1.12.0" />
  </ItemGroup>

</Project>

Output

References

Conclusion

We learned how to send email using ASP.NET Core 1.1 with MailKit in Visual Studio 2017. I hope, you liked this article. Please share your valuable suggestions and feedback.

Advertisements

Send Email To Multiple Email Addresses With Inline Image Using ASP.NET With C#


Introduction

In this article I will explain how to send multiple emails with Inline Image. Before reading this article you must read my previous email related article because I have explained some basics part in my previous article and changed few of the code part in new one. The following are my previous articles.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {
        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        
        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);

        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress email", "fromaddress password");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Net.Mime;

Multiple Email

The following code will help to split the Comma ‘”,” separated email in the given textbox ( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Inline Image Code

The following code will help to fetch the image and set into the inline of the email body.

        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);
        message.Body = mailbody;

Important Notes

  • Firstly, create one string that contain the html body with Inline image. In the above code “mailbody” is the string. It contains the html body.
  • Create an AlternateView object for those supporting the HTML content.
  • System.Net.Mime namespace contain the Image type and html format ( MediaTypeNames.Image.Jpeg & MediaTypeNames.Text.Html ).
  • Create a LinkedResource object for the Inline image to send.
  • Add a LinkedResource object to the AlternateView object.
  • Check the correct Image location otherwise it will throw an error.
  • Give same Image source id and LinkedResource ContentId.Like “<img src=\”cid:Email\” width=’600′ height=’300′>” & Picture1.ContentId = “Email“;

Design

1

Output

2

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with Inline Image using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Send Email To Multiple Email Addresses With Attachment Using ASP.NET With C#


Introduction

In my previous article I explained Send Email Using ASP.Net With C#. In this article I will explain how to send multiple emails with attachments. If you don’t bother about the code because I just change some codes in my previous article. ! Let’s start.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#23377771"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

        string mailbody = Txt_Bodycontent.Text;
        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress", "fromaddresspassword");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;

Multiple Email

The following code will help to split the Comma ‘”,” Separated email in the given textbox( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Attachment

If you want to send an attachment with email you can add the following code. Otherwise you just remove this part in the code.

if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#79547700"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

File Upload

If you want to select multiple files in a single file uploader, then you just add AllowMultiple=”true”.This is one of the option in ASP file upload.

<div>  
    <asp:FileUpload runat="server" ID="FileUpload2" AllowMultiple="true" />  
</div>

Design

output

Output

Capture

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with attachment using ASP.NET and C#. I hope this article is useful for all .NET beginners.

The server response was: 5.5.1 Authentication Required.



Error :

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

It’s a common issue we have faced in sending email.how to solve this check the following steps.

Solution:

  • Enter the correct login password.
  • To remove 2-Step Verification.
  • You have to enable login from other timezone / ip for your google account.To do this follow the link  and allow access by clicking the continue button.

  • Go to security settings at the following link and enable less secure apps . So that you will be able to login from all apps.

PublishedSMTP Server Requires a Secure Connection

Send Email Using ASP.Net With C#


Introduction

There are many more articles on Google for sending an email using ASP.NET and C#. This article explains some important functions and notable errors.

Code


    using System.IO;  
    using System.Net;  
    using System.Net.Mail;  
      
      
    string to = "toaddress@gmail.com"; //To address    
    string from = "fromaddress@gmail.com"; //From address    
    MailMessage message = new MailMessage(from, to);  
      
    string mailbody = "In this article you will learn how to send a email using Asp.Net & C#";  
    message.Subject = "Sending Email Using Asp.Net & C#";  
    message.Body = mailbody;  
    message.BodyEncoding = Encoding.UTF8;  
    message.IsBodyHtml = true;  
    SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
    System.Net.NetworkCredential basicCredential1 = new  
    System.Net.NetworkCredential("yourmail id", "Password");  
    client.EnableSsl = true;  
    client.UseDefaultCredentials = false;  
    client.Credentials = basicCredential1;  
    try   
    {  
        client.Send(message);  
    }   
      
    catch (Exception ex)   
    {  
        throw ex;  
    }  

We must add the following namespace:

using System.Net;    
using System.Net.Mail;  

Simple Mail Transfer Protocol (SMTP)

Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used in sending and receiving e-mail. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another. The messages can then be retrieved with an e-mail client using either POP or IMAP.

The following is a list of SMTP Server and Port Numbers:

Sl.No Mail Server SMTP Server( Host ) Port Number
1 Gmail smtp.gmail.com 587
2 Outlook smtp.live.com 587
3 Yahoo Mail smtp.mail.yahoo.com 465
4 Yahoo Mail Plus plus.smtp.mail.yahoo.com 465
5 Hotmail smtp.live.com 465
6 Office365.com smtp.office365.com 587
7 zoho Mail smtp.zoho.com 465

Important SMTP Class Properties:

  • Host: Server URL for SMTP (check the preceding table).
  • EnableSsl: Check your host accepts SSL Connections (True or False).
  • Port: Port Number of the SMTP server (check the preceding table).
  • Credentials: Valid login credentials for the SMTP server (the email address and password).
  • UseDefaultCredentials: When we set to True in UseDefaultCredentials then that specifies to allow authentication based on the credentials of the account used to send emails.

Common Error

The following error will occur commonly for everyone. How to solve this? Check my previous blog contents.

Summary

We learned how to send emails using ASP.NET and C#. I hope this article is useful for all .NET beginners.

%d bloggers like this: