Introduction
When you want to send email message, you must create an instances of MailMessage and SmtpClient classes. This classes are in System.Net.Mail namespace. In this example aj created method GetSmtpClient which returns SmtpClient object with paramers:
- host: represents IP or name of server user for smtp transactions
- port: represents port used for smtp transactions
- user: represents user name
- password: represents password to account
- enableSsl: specity whether use Secure Socket Layer (SSL) to encrypt the connection
Afther that I created MailMessage object. When you want to create html based message with resources (pictures ... etc), you must use LinkedResorce class. LinkedResource class represents an embedded external resource in email attachment, such as image. For every linked resource you must set ContentId which uniquely identifies resources. In example file "photo.jpg" was added with ContentId="photo".
For demostration purposes I used smtp.gmail.com server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace SendMail
{
class Program
{
static void Main(string[] args)
{
SmtpClient smtpClient = GetSmtpClient("smtp.gmail.com", 587, "GmailUserName@gmail.com", "password", true);
MailMessage mail = new MailMessage();
mail.From = new MailAddress("GmailUserName@gmail.com");
mail.To.Add("AddressTo@hotmail.com");
mail.Subject = "Test";
string htmlBody="";
htmlBody = htmlBody + "<img src=\"cid:photo\">" + Environment.NewLine;
mail.IsBodyHtml = true;
mail.Body = htmlBody;
AlternateView htmlview = default(AlternateView);
htmlview = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
LinkedResource imageResourceEs = new LinkedResource("photo.jpg");
imageResourceEs.ContentId = "photo";
imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlview.LinkedResources.Add(imageResourceEs);
mail.AlternateViews.Add(htmlview);
try
{
smtpClient.Send(mail);
}
catch (Exception t)
{
Console.WriteLine(t.Message);
}
}
static SmtpClient GetSmtpClient(string host, int port, string user, string password, bool enableSsl)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = host;
smtpClient.Port = port;
NetworkCredential cred = new NetworkCredential(user, password);
smtpClient.EnableSsl = enableSsl;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Timeout = 5000;
smtpClient.Credentials = cred;
return smtpClient;
}
}
}
Links
http://msdn.microsoft.com/en-us/library/system.net.mail.linkedresource.aspx