Click here to Skip to main content
11,502,559 members (62,346 online)
Click here to Skip to main content

Tagged as

Sending an Email in C# with or without attachments: generic routine.

, 3 Mar 2011 CPOL 56.3K 48
Rate this:
Please Sign up or sign in to vote.
Sending an email is not a real problem, but I am fed up with answering the question "How do I do it?" in Q&A . So, here is the generic routine I use to send an email, with or without attachments, so I can just point people at it!
/// <summary>
/// Send an email from [DELETED]
/// </summary>
/// <param name="to">Message to address</param>
/// <param name="body">Text of message to send</param>
/// <param name="subject">Subject line of message</param>
/// <param name="fromAddress">Message from address</param>
/// <param name="fromDisplay">Display name for "message from address"</param>
/// <param name="credentialUser">User whose credentials are used for message send</param>
/// <param name="credentialPassword">User password used for message send</param>
/// <param name="attachments">Optional attachments for message</param>
public static void Email(string to,
                         string body,
                         string subject,
                         string fromAddress,
                         string fromDisplay,
                         string credentialUser,
                         string credentialPassword,
                         params MailAttachment[] attachments)
    {
    string host = ConfigurationManager.AppSettings["SMTPHost"];
    body = UpgradeEmailFormat(body);
    try
        {
        MailMessage mail = new MailMessage();
        mail.Body = body;
        mail.IsBodyHtml = true;
        mail.To.Add(new MailAddress(to));
        mail.From = new MailAddress(fromAddress, fromDisplay, Encoding.UTF8);
        mail.Subject = subject;
        mail.SubjectEncoding = Encoding.UTF8;
        mail.Priority = MailPriority.Normal;
        foreach (MailAttachment ma in attachments)
            {
            mail.Attachments.Add(ma.File);
            }
        SmtpClient smtp = new SmtpClient();
        smtp.Credentials = new System.Net.NetworkCredential(credentialUser, credentialPassword);
        smtp.Host = host;
        smtp.Send(mail);
        }
    catch (Exception ex)
        {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("\nTo:" + to);
        sb.Append("\nbody:" + body);
        sb.Append("\nsubject:" + subject);
        sb.Append("\nfromAddress:" + fromAddress);
        sb.Append("\nfromDisplay:" + fromDisplay);
        sb.Append("\ncredentialUser:" + credentialUser);
        sb.Append("\ncredentialPasswordto:" + credentialPassword);
        sb.Append("\nHosting:" + host);
        ErrorLog(sb.ToString(), ex.ToString(), ErrorLogCause.EmailSystem);
        }
    }
"UpgradeEmailFormat" and "ErrorLog" are generic routines; you don't need the former, and can write the later yourself!
"MailAttachment" is a simple class you only need if you want to send attachments:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net.Mime;
using System.Net.Mail;
public class MailAttachment
    {
    #region Fields
    private MemoryStream stream;
    private string filename;
    private string mediaType;
    #endregion
    #region Properties
    /// <summary>
    /// Gets the data stream for this attachment
    /// </summary>
    public Stream Data { get { return stream; } }
    /// <summary>
    /// Gets the original filename for this attachment
    /// </summary>
    public string Filename { get { return filename; } }
    /// <summary>
    /// Gets the attachment type: Bytes or String
    /// </summary>
    public string MediaType { get { return mediaType; } }
    /// <summary>
    /// Gets the file for this attachment (as a new attachment)
    /// </summary>
    public Attachment File{ get {return new Attachment(Data, Filename, MediaType); } }
    #endregion
    #region Constructors
    /// <summary>
    /// Construct a mail attachment form a byte array
    /// </summary>
    /// <param name="data">Bytes to attach as a file</param>
    /// <param name="filename">Logical filename for attachment</param>
    public MailAttachment(byte[] data, string filename)
        {
        this.stream = new MemoryStream(data);
        this.filename = filename;
        this.mediaType = MediaTypeNames.Application.Octet;
        }
    /// <summary>
    /// Construct a mail attachment from a string
    /// </summary>
    /// <param name="data">String to attach as a file</param>
    /// <param name="filename">Logical filename for attachment</param>
    public MailAttachment(string data, string filename)
        {
        this.stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(data));
        this.filename = filename;
        this.mediaType = MediaTypeNames.Text.Html;
        }
    #endregion
    }

License

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

Share

About the Author

OriginalGriff
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?
Follow on   Google+

Comments and Discussions

 
QuestionAttachments Pin
deedcoder18-Aug-14 3:32
memberdeedcoder18-Aug-14 3:32 
QuestionMy Vote 5 Pin
anu_soft21-Apr-14 5:50
memberanu_soft21-Apr-14 5:50 
SuggestionVery useful Pin
Maimonides10-Aug-13 22:28
professionalMaimonides10-Aug-13 22:28 
GeneralRe: Very useful Pin
OriginalGriff10-Aug-13 22:44
protectorOriginalGriff10-Aug-13 22:44 
GeneralMy vote of 5 Pin
Member 381279319-Jun-13 7:06
memberMember 381279319-Jun-13 7:06 
QuestionHow to sent E-Mail to Gmail Pin
Mohamed Yahia27-Mar-13 3:03
memberMohamed Yahia27-Mar-13 3:03 
AnswerRe: How to sent E-Mail to Gmail Pin
gailmarboo30-Apr-13 6:56
membergailmarboo30-Apr-13 6:56 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib18-Feb-13 17:03
memberS. M. Ahasan Habib18-Feb-13 17:03 
GeneralRe: each. Pin
itb.hari6-Mar-11 22:57
memberitb.hari6-Mar-11 22:57 
GeneralRe: The reason is because I have to deal with huge chunks of rep... Pin
itb.hari6-Mar-11 22:54
memberitb.hari6-Mar-11 22:54 
GeneralReason for my vote of 5 Useful code. Pin
ProEnggSoft26-Feb-12 22:31
memberProEnggSoft26-Feb-12 22:31 
GeneralReason for my vote of 5 nice Pin
Uday P.Singh9-Dec-11 21:30
memberUday P.Singh9-Dec-11 21:30 
GeneralReason for my vote of 5 short and precise.. :-) Pin
Avinash Tiwari MCA23-Nov-11 0:06
memberAvinash Tiwari MCA23-Nov-11 0:06 
GeneralReason for my vote of 5 Short and to the point, my 5. --SA Pin
SAKryukov2-Jul-11 19:29
mvpSAKryukov2-Jul-11 19:29 
GeneralReason for my vote of 5 Great article Pin
mjbohn10-Apr-11 6:29
membermjbohn10-Apr-11 6:29 
GeneralReason for my vote of 5 Nice and simple - Good answer to a f... Pin
Espen Harlinn13-Mar-11 1:19
mvpEspen Harlinn13-Mar-11 1:19 
GeneralReason for my vote of 2 There's no disposal of any of these ... Pin
DustyBottoms10-Mar-11 6:04
memberDustyBottoms10-Mar-11 6:04 
GeneralReason for my vote of 5 A nice and simple way of putting thi... Pin
itb.hari8-Mar-11 7:01
memberitb.hari8-Mar-11 7:01 
GeneralAnyways fixed the issue with bigger files. Add a SMTPClient ... Pin
itb.hari6-Mar-11 22:55
memberitb.hari6-Mar-11 22:55 
GeneralRe: Upload? Doesn't surprise me at all. 100s may not be enough f... Pin
OriginalGriff6-Mar-11 23:20
mvpOriginalGriff6-Mar-11 23:20 
GeneralI seem to be getting a Operation Timed Out Exception when tr... Pin
itb.hari6-Mar-11 22:13
memberitb.hari6-Mar-11 22:13 
GeneralRe: I am so glad you don't have my email address... 50MB email a... Pin
OriginalGriff6-Mar-11 22:31
mvpOriginalGriff6-Mar-11 22:31 
GeneralReason for my vote of 5 Excellent solution, addressing rathe... Pin
DrABELL3-Mar-11 3:43
memberDrABELL3-Mar-11 3:43 
GeneralReason for my vote of 5 Great thanks :) yes I hope this will... Pin
EdMan1962-Mar-11 20:23
memberEdMan1962-Mar-11 20:23 
GeneralReason for my vote of 5 Great Tip OG, Nice share. Pin
thatraja2-Mar-11 7:19
mvpthatraja2-Mar-11 7:19 

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
Web04 | 2.8.150520.1 | Last Updated 3 Mar 2011
Article Copyright 2011 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid