C# code to send HTML page with inline images in mail body as inline image
C# page
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Xml;
using System.IO;
class Program
{
static void Main(string[] args)
{
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("yourusername@gmail.com");
mail.To.Add("yourusername@gmail.com");
//set the content
mail.Subject = "Sucess Fully Sent the HTML and COntent of mail";
//first we create the Plain Text part
string plainText = "Non HTML Plane Text Message for Non HTML enable mode";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain");
XmlTextReader reader = new XmlTextReader(@"C:\..\Windows\your path\HTMLPage.htm");
string[] address = new string[30];
string finalHtml = "";
var i = -1;
while (reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{ // The node is an element.
if (reader.AttributeCount <= 1)
{
if (reader.Name == "img")
{
finalHtml += "<" + reader.Name;
while (reader.MoveToNextAttribute())
{
if (reader.Name == "src")
{
i++;
address[i] = reader.Value;
address[i] = address[i].Remove(0, 8);
finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString();
}
else
{
finalHtml += " " + reader.Name + "='" + reader.Value + "'";
}
}
finalHtml += ">";
}
else
{
finalHtml += "<" + reader.Name;
while (reader.MoveToNextAttribute())
{
finalHtml += " " + reader.Name + "='" + reader.Value + "'";
}
finalHtml += ">";
}
}
}else if( reader.NodeType== XmlNodeType.Text)
{ //Display the text in each element.
finalHtml +=reader.Value;
}else if(reader.NodeType== XmlNodeType.EndElement){
//Display the end of the element.
finalHtml +="</" + reader.Name;
finalHtml += ">";
}
}
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html");
LinkedResource[] logo = new LinkedResource[i+1];
for (int j = 0; j <= i; j++)
{
logo[j] = new LinkedResource(address[j]);
logo[j].ContentId = "chartlogo" + j;
htmlView.LinkedResources.Add(logo[j]);
}
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new NetworkCredential(
"yourusername@gmail.com", "your password");
smtp.EnableSsl = true;
Console.WriteLine();
smtp.Send(mail);
}
}
HTMLPage.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>HTML Page to Send Mail </title></head>
<body>
<table border= "0" >
<tr>
<td>Chart1</td>
<td>Chart2</td>
<td>Chart3</td>
</tr>
<tr>
<td><img src = "file:///C:/Users/Windows/Desktop/ChartSnap/1.jpg" /></td>
<td><img src = "file:///C:/Users/Windows/Desktop/ChartSnap/2.jpg" /></td>
<td><img src = "file:///C:/Users/Windows/Desktop/ChartSnap/3.jpg" /></td>
</tr><tr>
<td><img src = "file:///C:/Users/Windows/Desktop/ChartSnap/4.jpg" /></td>
</tr>
</table>
</body>
</html>
No comments:
Post a Comment