Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

C# Code Snippet to Send an Email with Attachment from Outlook, Yahoo, HotMail, AOL and Gmail

Rate me:
Please Sign up or sign in to vote.
4.88/5 (71 votes)
19 May 2018CPOL2 min read 554.4K   108   75
Using this code snippet, user would be able to send an email with attachment through Outlook, Yahoo, AOL, HOTMAIL and Gmail.

Introduction

Using this code snippet, the user would be able to send an email with attachment through Outlook, Yahoo, AOL, HOTMAIL and Gmail.

Background

There is already loads of information that is available on the internet for the same purpose. But not all code is placed in one place. So here is my small effort to accumulate all the code at one place and that is nothing better than CodeProject. Hopefully, it will be helpful for beginners or whoever is in need of it.

Using the Code

Name Space

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using Outlook = Microsoft.Office.Interop.Outlook;

Block Diagram (SMTP Setting for Various Client)

Below is the block diagram for the SMTP settings I have used to send out an email from various client providers.

sendEmailSettings.jpg

Wherever needed, I have explained the code in detail. The code is self explanatory, anyway for the same, I have included comments. So here is the code snippet to achieve your purpose.

1. Using Outlook

To send an email using Outlook, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll.

For the same, follow the below steps:

  1. Go to your solution explorer.
  2. Click on add a reference.
  3. Click on .NET Tab.
  4. Go through the DLL and select Microsoft.Office.Interop.Outlook.dll correctly.

    AddReferece.jpg

  5. When you have selected the correct reference, you select the “OK” button and this reference will be added to your project under references.

    Mcrosoftdll.jpg

  6. Now we need to add a reference in our class to the Outlook reference we have added to the project in our previous example.
C#
using Outlook = Microsoft.Office.Interop.Outlook;

And finally, the code would look something like this:

C#
//method to send email to outlook
public void sendEMailThroughOUTLOOK()
{
    try
    {
    // Create the Outlook application.
    Outlook.Application oApp = new Outlook.Application();
    // Create a new mail item.
    Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
    // Set HTMLBody. 
    //add the body of the email
    oMsg.HTMLBody = "Hello, Jawed your message body will go here!!";
    //Add an attachment.
    String sDisplayName = "MyAttachment";
    int iPosition = (int)oMsg.Body.Length + 1;
    int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
    //now attached the file
    Outlook.Attachment oAttach = oMsg.Attachments.Add
                                 (@"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);
    //Subject line
    oMsg.Subject = "Your Subject will go here.";
    // Add a recipient.
    Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
    // Change the recipient in the next line if necessary.
    Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("jawed.ace@gmail.com");
    oRecip.Resolve();
    // Send.
    oMsg.Send();
    // Clean up.
    oRecip = null;
    oRecips = null;
    oMsg = null;
    oApp = null;
     }//end of try block
    catch (Exception ex)
    {
    }//end of catch
}//end of Email Method

2. Using HOTMAIL

To send an email using HotMail, we need to add a reference to the dynamic link library for Hotmail/Gmail/AOL/Yahoo which is called System.Net.Mail.

For the same, follow the below steps:

  1. Go to solution explorer of your project
  2. Select add a reference
  3. Click on .NET Tab
  4. Go through the DLL and select System.Net.Mail
  5. When you have selected the correct reference, you select the “OK” button and this reference will be added to your project under references.
  6. Now we need to add a reference in our class to the Hotmail/gmail/aol/yahoo reference we have added to the project.
C#
using System.Net.Mail;

Note: The HOTMAIL SMTP Server requires an encrypted connection (SSL) on port 25.

And finally, the code would look something like this:

C#
//method to send email to HOTMAIL
public void sendEMailThroughHotMail()
{
    try
    { 
    //Mail Message
        MailMessage mM = new MailMessage();
        //Mail Address
        mM.From = new MailAddress("sender@hotmail.com");
        //receiver email id
        mM.To.Add("rcver@gmail.com");
        //subject of the email
        mM.Subject = "your subject line will go here";
        //deciding for the attachment
        mM.Attachments.Add(new Attachment(@"C:\\attachedfile.jpg"));
        //add the body of the email
        mM.Body = "Body of the email";
        mM.IsBodyHtml = true;
        //SMTP client
        SmtpClient sC = new SmtpClient("smtp.live.com");
        //port number for Hot mail
        sC.Port = 25;
        //credentials to login in to hotmail account
        sC.Credentials = new NetworkCredential("sender@hotmail.com","HotMailPassword");
        //enabled SSL
        sC.EnableSsl = true;
        //Send an email
        sC.Send(mM);
    }//end of try block
    catch (Exception ex)
    {
    
    }//end of catch
}//end of Email Method HotMail

3. Using Yahoo!

C#
//Method to send email from YAHOO!!
public void sendEMailThroughYahoo()
{
    try
    {
        //mail message
        MailMessage mM = new MailMessage();
        //Mail Address
        mM.From = new MailAddress("sender@yahoo.com");
        //emailid to send
        mM.To.Add("recvEmailid@gmail.com");
        //your subject line of the message
        mM.Subject = "your subject line will go here.";
        //now attached the file
        mM.Attachments.Add(new Attachment(@"C:\\attachedfile.jpg"));
        //add the body of the email
        mM.Body = "Your Body of the email.";
        mM.IsBodyHtml = false;
        //SMTP 
        SmtpClient SmtpServer = new SmtpClient();
        //your credential will go here
        SmtpServer.Credentials = new System.Net.NetworkCredential("sender@yahoo.com", "password");
        //port number to login yahoo server
        SmtpServer.Port = 587;
        //yahoo host name
        SmtpServer.Host = "smtp.mail.yahoo.com";
        //Send the email
        SmtpServer.Send(mM);
    }//end of try block
    catch (Exception ex)
    {
    }//end of catch
}//end of Yahoo Email Method

4. Using AOL

C#
//Method to send email from YAHOO!!
public void sendEMailThroughAOL()
{
    try
    {
         //mail message
        MailMessage mM = new MailMessage();
        //Mail Address
        mM.From = new MailAddress("sender@aol.com");
        //emailid to send
        mM.To.Add("recvEmailid@gmail.com");
        //your subject line of the message
        mM.Subject = "your subject line will go here.";
        //now attached the file
        mM.Attachments.Add(new Attachment(@"C:\\attachedfile.jpg"));
        //add the body of the email
        mM.Body = "Your Body of the email.";
        mM.IsBodyHtml = false;
        //SMTP 
        SmtpClient SmtpServer = new SmtpClient();
        //your credential will go here
        SmtpServer.Credentials = new System.Net.NetworkCredential("sender@aol.com", "AOLpassword");
        //port number to login yahoo server
        SmtpServer.Port = 587;
        //yahoo host name
        SmtpServer.Host = "smtp.aol.com";
        //Send the email
        SmtpServer.Send(mM);
    }//end of try block
    catch (Exception ex)
    {
 
    }//end of catch
}//end of AOLEmail Method

5. Using Gmail

Note: The GMAIL SMTP Server requires an encrypted connection (SSL) on port 487.

C#
//method to send email to Gmail
public void sendEMailThroughGmail()
{
    try
    {
        //Mail Message
        MailMessage mM = new MailMessage();
        //Mail Address
        mM.From = new MailAddress("sender@gmail.com");
        //receiver email id
        mM.To.Add("rcver@gmail.com");
        //subject of the email
        mM.Subject = "your subject line will go here";
        //deciding for the attachment
        mM.Attachments.Add(new Attachment(@"C:\\attachedfile.jpg"));
        //add the body of the email
        mM.Body = "Body of the email";
        mM.IsBodyHtml = true;
        //SMTP client
        SmtpClient sC = new SmtpClient("smtp.gmail.com");
        //port number for Gmail mail
        sC.Port = 587;
        //credentials to login in to Gmail account
        sC.Credentials = new NetworkCredential("sender@gmail.com", "GmailPassword");
        //enabled SSL
        sC.EnableSsl = true;
        //Send an email
        sC.Send(mM);
    }//end of try block
    catch (Exception ex)
    {
 
    }//end of catch
}//end of Email Method

Already, I am using the above code snippet for my automation purposes and it's working fine for me!!

http://jawedm.blogspot.com

Thank you!!

Feel free to provide your comments and vote.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
http://jawedm.blogspot.com

Contact me for Freelancing at jawed.ace@gmail.com
Free to go anywhere,ready to learn anything...

Comments and Discussions

 
QuestionHow to get email ID and subject from textbox Pin
Mohammad Imran122-Jan-23 22:46
Mohammad Imran122-Jan-23 22:46 
QuestionNot releasing the resources? Pin
Server Automator30-Aug-20 14:13
professionalServer Automator30-Aug-20 14:13 
QuestionDownload fails Pin
Member 1378694321-May-19 10:15
Member 1378694321-May-19 10:15 
QuestionHow to add from mail and calender as attachment Pin
Member 103787677-Nov-18 3:43
Member 103787677-Nov-18 3:43 
Bugdon't see all the code and the link is broken ... Pin
Member 1396067724-Aug-18 14:58
Member 1396067724-Aug-18 14:58 
QuestionThanks a ton Pin
Suryadip Basu19-Jul-18 21:12
Suryadip Basu19-Jul-18 21:12 
QuestionZip file is missing Pin
FredWah23-May-18 5:00
FredWah23-May-18 5:00 
QuestionGood work - could be more OO Pin
Kirk Wood22-May-18 3:32
Kirk Wood22-May-18 3:32 
QuestionUsing API Gmail for send email Pin
kiquenet.com22-May-18 0:22
professionalkiquenet.com22-May-18 0:22 
SuggestionA quick one-liner Pin
DavidCovey9-May-17 16:38
DavidCovey9-May-17 16:38 
QuestionUsing Step 1 process error Pin
mdigankar19-Sep-16 19:23
mdigankar19-Sep-16 19:23 
AnswerRe: Using Step 1 process error Pin
Member 1031557228-May-23 21:08
Member 1031557228-May-23 21:08 
QuestionHello Pin
Member 1185209230-Dec-15 7:08
Member 1185209230-Dec-15 7:08 
QuestionDevelop to Outlook without having Outlook Pin
Plinio Guimarães31-Jul-15 6:48
Plinio Guimarães31-Jul-15 6:48 
Questionselect profile from multiple profile Pin
keyur soni26-Feb-15 3:34
keyur soni26-Feb-15 3:34 
SuggestionWorked well for me, but without Signature. Pin
ZinusMero14-Jan-15 15:30
ZinusMero14-Jan-15 15:30 
QuestionCould not send the e-mail Pin
Member 109250677-Aug-14 12:44
Member 109250677-Aug-14 12:44 
QuestionZip file not attached using above code in outlook Pin
gaytri.nagpal6-Aug-14 5:33
gaytri.nagpal6-Aug-14 5:33 
QuestionHow to choose from multiple profiles in Outlook Pin
Avirup Das22-Jul-14 20:06
professionalAvirup Das22-Jul-14 20:06 
QuestionThanks Pin
Varun Warrier15-Jul-14 8:30
Varun Warrier15-Jul-14 8:30 
QuestionShouldn't you release the COM objects like Outlook.MailItem ? Pin
aDoubleSo21-Mar-14 5:52
aDoubleSo21-Mar-14 5:52 
QuestionC# Code snippet to send an Email with attachment from Outlook Pin
Member 1057595925-Feb-14 20:18
Member 1057595925-Feb-14 20:18 
QuestionAutomated Mails through Outlook Pin
Aditya_12328-Dec-13 9:18
Aditya_12328-Dec-13 9:18 
QuestionC# Code snippet to send an Email with attachment from Outlook : method to send email to outlook Pin
Suhail AG23-Oct-13 3:00
Suhail AG23-Oct-13 3:00 
QuestionMy vote of 5 Pin
hkn050920-Sep-13 8:33
hkn050920-Sep-13 8:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.