// you're reading...

.NET

.NET: Sending a HTML Email with an Attachment

A reader who read the earlier post titled ColdFusion & .NET: Send an Email, asked a couple of questions on sending the email in .NET.  He was asking how you send an HTML email and secondly, add an attachment.  So I put together a quick sample of doing this.  I have also included the full code behind this time.  Also remember that all my .NET samples are using C#.

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

public partial class html_email : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string BodyText = "

Row 1 Row 2

";

System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("to@email.com");
message.Subject = "Your Test HTML Email";
message.From = new System.Net.Mail.MailAddress("from@email.com");

message.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(BodyText, null, "text/html");
message.AlternateViews.Add(htmlView);

Attachment att = new Attachment(Server.MapPath("harvick.jpg"));
message.Attachments.Add(att);

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("mail.someserver.com");
smtp.Credentials = new NetworkCredential("username@email.com", "password");

smtp.Send(message);
}
}

Discussion

4 Responses to “.NET: Sending a HTML Email with an Attachment”

  1. Now lets see .NET dynamically creaet a PDF and attach it like CF can: http://www.coldfusionjedi.com/index.cfm/2009/1/22/Ask-a-Jedi-Sending-a-dynamic-PDF-via-email

    Posted by James | February 13, 2009, 1:04 AM
  2. Now lets see .NET dynamically creaet a PDF and attach it like CF can: http://www.coldfusionjedi.com/index.cfm/2009/1/22/Ask-a-Jedi-Sending-a-dynamic-PDF-via-email

    Posted by James | February 12, 2009, 8:04 PM
  3. …and, as usual, if you *don’t* enjoy typing, think “CF”
    <cfmail to=”to@email.com” from=”from@email.com” subject=”Your Test HTML Email” charset=”utf-8″ type=”html” server=”mail.someserver.com” username=”username@email.com” password=”password” mimeattach=”harvick.jpg”><table border=1><tr><td>Row 1</td><td>Row 2</td></tr></table></cfmail>

    Posted by John Bliss | February 13, 2009, 12:52 PM
  4. …and, as usual, if you *don’t* enjoy typing, think “CF”
    <cfmail to=”to@email.com” from=”from@email.com” subject=”Your Test HTML Email” charset=”utf-8″ type=”html” server=”mail.someserver.com” username=”username@email.com” password=”password” mimeattach=”harvick.jpg”><table border=1><tr><td>Row 1</td><td>Row 2</td></tr></table></cfmail>

    Posted by John Bliss | February 13, 2009, 7:52 AM

Post a comment

Categories