Click here to Skip to main content
11,637,002 members (69,047 online)
Click here to Skip to main content

Tagged as

C# Code snippet to send an Email with attachment from Outlook, Yahoo, HotMail, AOL and Gmail

, 11 Mar 2011 CPOL 370.3K 352 58
Rate this:
Please Sign up or sign in to vote.
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 user would be able to send an email with attachment through Outlook, Yahoo, AOL, HOTMAIL and Gmail.

Background

Already loads of information are available on internet for the same purpose. But not all the code is placed at 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 the beginners or whoever in needs of it.

Using the Code

Name Space

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 explain the code in details. The codes are self explanatory, any way 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.
  5. AddReferece.jpg

  6. when you have selected the correct reference you select the “OK” button and this reference will be added to your project under references.
  7. Mcrosoftdll.jpg

  8. Now we need to add a reference in our class to the Outlook reference we have added to the project in our previous example.
using Outlook = Microsoft.Office.Interop.Outlook;
And finally the code would look something like this:
                    
//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
  6. be added to your projectunder references.

  7. Now we need to add a reference in our class to the Hotmail/gmail/aol/yahoo reference we have
added to the project.
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:

//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!

//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

//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.
//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 purpose and its 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)

Share

About the Author

jawed.ace
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...

You may also be interested in...

Comments and Discussions

 
Questionselect profile from multiple profile Pin
keyur soni26-Feb-15 3:34
memberkeyur soni26-Feb-15 3:34 
SuggestionWorked well for me, but without Signature. Pin
ZinusMero14-Jan-15 15:30
memberZinusMero14-Jan-15 15:30 
QuestionCould not send the e-mail Pin
Member 109250677-Aug-14 12:44
memberMember 109250677-Aug-14 12:44 
QuestionZip file not attached using above code in outlook Pin
gaytri.nagpal6-Aug-14 5:33
membergaytri.nagpal6-Aug-14 5:33 
QuestionHow to choose from multiple profiles in Outlook Pin
Avirup Das22-Jul-14 20:06
memberAvirup Das22-Jul-14 20:06 
QuestionThanks Pin
Varun Warrier15-Jul-14 8:30
memberVarun Warrier15-Jul-14 8:30 
QuestionShouldn't you release the COM objects like Outlook.MailItem ? Pin
aDoubleSo21-Mar-14 5:52
memberaDoubleSo21-Mar-14 5:52 
QuestionC# Code snippet to send an Email with attachment from Outlook Pin
Member 1057595925-Feb-14 20:18
memberMember 1057595925-Feb-14 20:18 
QuestionAutomated Mails through Outlook Pin
Aditya_12328-Dec-13 9:18
memberAditya_12328-Dec-13 9:18 
QuestionC# Code snippet to send an Email with attachment from Outlook : method to send email to outlook Pin
Member 1017736723-Oct-13 3:00
memberMember 1017736723-Oct-13 3:00 
QuestionMy vote of 5 Pin
hkn050920-Sep-13 8:33
memberhkn050920-Sep-13 8:33 
GeneralMy vote of 5 Pin
Iván Golo9-Jul-13 12:41
memberIván Golo9-Jul-13 12:41 
QuestionEmail from C-Sharp Pin
boss prabu17-Mar-13 7:26
memberboss prabu17-Mar-13 7:26 
GeneralMy vote of 5 Pin
patrdjok11-Dec-12 0:03
memberpatrdjok11-Dec-12 0:03 
QuestionGreat work Pin
Member 93447555-Oct-12 4:40
memberMember 93447555-Oct-12 4:40 
QuestionWorks great but..... Pin
raven2911b6-Sep-12 7:44
memberraven2911b6-Sep-12 7:44 
QuestionPLS reply me very urgent--open calculator using vb.net Pin
Aravindbpanchu26-Jul-12 22:53
memberAravindbpanchu26-Jul-12 22:53 
GeneralMy vote of 5 Pin
AndrewsCP25-Jun-12 18:45
memberAndrewsCP25-Jun-12 18:45 
GeneralMy vote of 5 Pin
kungPowellchicken25-Jun-12 11:11
memberkungPowellchicken25-Jun-12 11:11 
Questionhow would i use this for common mail server Pin
baskaran chellasamy22-Apr-12 21:59
memberbaskaran chellasamy22-Apr-12 21:59 
AnswerAlternative link to download source code Pin
jawed.ace21-Mar-12 3:25
memberjawed.ace21-Mar-12 3:25 
GeneralRe: Alternative link to download source code Pin
Aravindbpanchu26-Jul-12 22:56
memberAravindbpanchu26-Jul-12 22:56 
Questiongood work Pin
Mehmooda5-Mar-12 0:40
memberMehmooda5-Mar-12 0:40 
the download link aint working. other than tht good work with the code. its working fine Smile | :) thanks
AnswerRe: good work Pin
jawed.ace21-Mar-12 3:22
memberjawed.ace21-Mar-12 3:22 
Generalthanks for this information........... this is very useful t... Pin
DhavalAshodariya11-Jan-12 17:09
memberDhavalAshodariya11-Jan-12 17:09 
GeneralRe: Thank you very much for you comments :) let me know for any ... Pin
jawed.ace24-Jan-12 19:20
memberjawed.ace24-Jan-12 19:20 
GeneralReason for my vote of 5 nice share thanks Pin
Ahmed_3bdo8-Jan-12 11:00
memberAhmed_3bdo8-Jan-12 11:00 
GeneralRe: Thanks Ahmed for your votes and nice words. ~jawed http://ja... Pin
jawed.ace24-Jan-12 19:21
memberjawed.ace24-Jan-12 19:21 
GeneralThanks very much for this information it's very useful for m... Pin
Joshua Olguin12-Dec-11 11:25
memberJoshua Olguin12-Dec-11 11:25 
GeneralRe: Thanks for vote and comments. Please let me know for any kin... Pin
jawed.ace24-Jan-12 19:22
memberjawed.ace24-Jan-12 19:22 
GeneralI am not able to download the source code! Pin
Mihir Pandya23-Nov-11 3:08
memberMihir Pandya23-Nov-11 3:08 
GeneralRe: I am not able to download the source code! Pin
asrrar21-Mar-12 2:23
memberasrrar21-Mar-12 2:23 
GeneralRe: I am not able to download the source code! Pin
asrrar21-Mar-12 2:24
memberasrrar21-Mar-12 2:24 
AnswerRe: I am not able to download the source code! Pin
jawed.ace21-Mar-12 3:23
memberjawed.ace21-Mar-12 3:23 
GeneralGood Job.. :-) Pin
version_2.011-Nov-11 17:46
memberversion_2.011-Nov-11 17:46 
GeneralReason for my vote of 5 good job!!! Pin
neilfan201130-Aug-11 20:47
memberneilfan201130-Aug-11 20:47 
GeneralGetting error at second statement. I use OutLook 2003 and re... Pin
kshitij verma28-Jul-11 19:09
memberkshitij verma28-Jul-11 19:09 
GeneralReason for my vote of 5 THE Robust piece of code.... Very in... Pin
Syed Shahid Hussain28-Jun-11 15:04
memberSyed Shahid Hussain28-Jun-11 15:04 
GeneralRe: Thanks syed. i replied to your question. have a look and let... Pin
jawed.ace29-Jun-11 19:38
memberjawed.ace29-Jun-11 19:38 
GeneralVery good post. very help full. Just awesome. Thank you. Pin
PRITOM KUMAR MONDAL26-Jun-11 17:56
memberPRITOM KUMAR MONDAL26-Jun-11 17:56 
GeneralRe: Thank you very much Pritom. Pin
jawed.ace27-Jun-11 5:55
memberjawed.ace27-Jun-11 5:55 
GeneralReason for my vote of 5 nice article........ thanks for shar... Pin
jugalpanchal18-Mar-11 0:00
memberjugalpanchal18-Mar-11 0:00 
GeneralRe: You are most welcome and thank you very much!!. ~jawed Pin
jawed.ace18-Mar-11 6:58
memberjawed.ace18-Mar-11 6:58 
GeneralReason for my vote of 5 Thanks for sharing! Pin
Member 771943315-Mar-11 7:09
memberMember 771943315-Mar-11 7:09 
GeneralReason for my vote of 5 Great idea to present "complete" cod... Pin
Joe Harbin15-Mar-11 3:46
memberJoe Harbin15-Mar-11 3:46 
GeneralRe: Thank you very much for your appreciation!! Pin
jawed.ace15-Mar-11 6:03
memberjawed.ace15-Mar-11 6:03 
GeneralReason for my vote of 5 Nice collection. Thanks for sharing. Pin
JF201514-Mar-11 22:16
memberJF201514-Mar-11 22:16 
GeneralRe: Thank you very much for your vote. ~jawed Pin
jawed.ace15-Mar-11 6:04
memberjawed.ace15-Mar-11 6:04 
QuestionException after send Pin
Member 376823231-Aug-11 5:18
memberMember 376823231-Aug-11 5:18 
Questionerror Pin
kshitij verma5-Aug-11 22:05
memberkshitij verma5-Aug-11 22:05 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150728.1 | Last Updated 11 Mar 2011
Article Copyright 2011 by jawed.ace
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid