Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Aspose.Email for .NET
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Gists of Aspose.Email for .NET
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Aspose.Email.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Aspose.Email.Properties.Settings>
<setting name="SmtpDiagnosticLog" serializeAs="String">
<value>Aspose.Email.SMTP.log</value>
</setting>
</Aspose.Email.Properties.Settings>
</applicationSettings>
</configuration>
Reply-To: reply@reply.com
From: sender@sender.com
To: guangzhou@guangzhoo.com
Subject: test mail
Date: 6 Mar 2006 8:2:2 +0800
X-Mailer: Aspose.Email
Examples-CSharp
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
client.EnableSsl = true;
client.SecurityMode = ImapSslSecurityMode.Implicit;
// Set proxy address, port and proxy
string proxyAddress = "192.168.203.142";
int proxyPort = 1080;
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, Aspose.Email.Protocols.Proxy.SocksVersion.SocksV5);
client.SocksProxy = proxy;
client.SelectFolder("Inbox");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
static void Main(string[] args)
{
// The authorizationCode should be replaced with your value. To get authorizationCode use the URL bellow: https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F
string authorizationCode = "4/zx4_I4ZhhUdmgLdsejpjeMkwAAMs.kk7o1Qx9U28VOl05ti8ZT3Y1uIlidQI"; // authorizationCode should be replaced with new value !!!!!!!
string accessToken = GetAccessToken(authorizationCode);
AccessSMTPServer(accessToken);
AccessIMAPServer(accessToken);
}
static void AccessSMTPServer(string accessToken)
{
MailMessage message = new MailMessage("user1@testaccount1913.narod2.ru","user1@testaccount1913.narod2.ru","NETWORKNET-33499 - " + Guid.NewGuid().ToString(),"Access to SMTP servers using OAuth");
using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "user1@testaccount1913.narod2.ru", accessToken, true))
{
client.Timeout = 400000;
client.SecurityMode = SmtpSslSecurityMode.Implicit;
client.EnableSsl = true;
client.Send(message);
}
}
static void AccessIMAPServer(string accessToken)
{
using (ImapClient client = new ImapClient("imap.gmail.com", 993, "user1@testaccount1913.narod2.ru", accessToken, true))
{
client.EnableSsl = true;
client.SecurityMode = ImapSslSecurityMode.Implicit;
client.Connect();
client.SelectFolder("Inbox");
ImapMessageInfoCollection messageInfoCol = client.ListMessages();
}
}
internal static string GetAccessToken(string authorizationCode)
{
string actionUrl = "https://accounts.google.com/o/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string encodedParameters = string.Format("client_id={1}&code={0}&client_secret={2}&redirect_uri={3}&grant_type={4}",
HttpUtility.UrlEncode(authorizationCode),
HttpUtility.UrlEncode("929645059575.apps.googleusercontent.com"),
HttpUtility.UrlEncode("USnH5eQRsC4XrjJbpGG7WVq5"),
HttpUtility.UrlEncode("urn:ietf:wg:oauth:2.0:oob"),
HttpUtility.UrlEncode("authorization_code"));
byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
request.ContentLength = requestData.Length;
if (requestData.Length > 0)
using (Stream stream = request.GetRequestStream())
stream.Write(requestData, 0, requestData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseText = null;
using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
responseText = reader.ReadToEnd();
string accessToken = null;
foreach (string sPair in responseText.Replace("{", "").Replace("}", "").Replace("\"", "").
Split(new string[] { ",\n" }, StringSplitOptions.None))
{
string[] pair = sPair.Split(':');
if ("access_token" == pair[0].Trim())
{
accessToken = pair[1].Trim();
break;
}
}
return accessToken;
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of the MailMessage class and Attachment class
MailMessage message = new MailMessage();
message.From = "sender@sender.com";
message.To.Add("receiver@receiver.com");
// Adding 1st attachment, Create an instance of Attachment class, Load or add an attachment, Save the attachment then add the attachment to the message
Attachment attachment;
attachment = new Attachment(@"d:\1.txt");
attachment.Save(@"e:\2.txt");
message.Attachments.Add(attachment);
// Create an instance of the SmtpClient Class and Specify your mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
try
{
// Client.Send will send this message
client.Send(message);
Console.WriteLine("Message sent");
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create a message and Subscribe to the Inbox folder ans Append the newly created message
MailMessage message = new MailMessage("user@domain1.com","user@domain2.com","subject","message");
imap.SelectFolder(ImapFolderInfo.InBox);
imap.SubscribeFolder(imap.CurrentFolder.Name);
imap.AppendMessage(imap.CurrentFolder.Name, msg);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory and Instantiate an instance of MailPrinter
string dataDir = RunExamples.GetDataDir_Email();
Printing.MailPrinter printer = new Printing.MailPrinter();
printer.DpiX = 300;
printer.DpiY = 300;
MailMessage msg = MailMessage.Load(dataDir + "Message.msg", MessageFormat.Msg);
printer.Print(msg, dataDir + "AdjustTargetDPI_out.tiff", Printing.PrintFormat.Tiff);
For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Aspose.Email.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Aspose.Email.Properties.Settings>
<setting name="ImapDiagnosticLog" serializeAs="String">
<value>Aspose.Email.IMAP.log</value>
</setting>
<setting name="ImapDiagnosticLog_UseDate" serializeAs="String">
<value>True</value>
</setting>
</Aspose.Email.Properties.Settings>
</applicationSettings>
</configuration>
For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Aspose.Email.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Aspose.Email.Properties.Settings>
<setting name="Pop3DiagnosticLog" serializeAs="String">
<value>Aspose.Email.Pop3.log</value>
</setting>
<setting name="Pop3DiagnosticLog_UseDate" serializeAs="String">
<value>True</value>
</setting>
</Aspose.Email.Properties.Settings>
</applicationSettings>
</configuration>
For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Aspose.Email.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Aspose.Email.Properties.Settings>
<setting name="SmtpDiagnosticLog" serializeAs="String">
<value>Aspose.Email.SMTP.log</value>
</setting>
</Aspose.Email.Properties.Settings>
</applicationSettings>
</configuration>
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify From, To, Subject and Body
message.From = txtFrom.Text;
message.To = txtTo.Text;
message.Subject = "My First Mail";
message.Body = txtBody.Text;
// Send email using SmtpClient, Create an instance of the SmtpClient Class and Specify the mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
// Specify the mailing host server, Username, Password and Port
client.Host = "mail.server.com";
client.Username = "username";
client.Password = "password";
client.Port = 25;
client.Send(message);
// Notify the user that a message has been sent
MessageBox.Show("Message Sent");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Clear the items in the listbox
lstMessages.Items.Clear();
// Create instance of ExchangeClient class by giving credentials and Call ListMessages method to list messages info from Inbox
ExchangeClient client = new ExchangeClient(txtExchangeServer.Text, txtUsername.Text, txtPassword.Text, txtDomain.Text);
ExchangeMessageInfoCollection msgCollection = client.ListMessages(client.MailboxInfo.InboxUri);
// Loop through the collection to display the basic information
foreach (ExchangeMessageInfo msgInfo in msgCollection)
{
string strMsgInfo = "Subject: " + msgInfo.Subject + " == From: " + msgInfo.From.ToString() + " == To: " + msgInfo.To.ToString();
lstMessages.Items.Add(strMsgInfo);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Creates an instance of the class ImapClient by specified the host, username and password
ImapClient client = new ImapClient("localhost", "username", "password");
try
{
client.SelectFolder(ImapFolderInfo.InBox);
String strTemp;
strTemp = "You have " + client.CurrentFolder.TotalMessageCount.ToString() + " messages in your account.";
// Gets number of messages in the folder, Disconnects to imap server.
MessageBox.Show(strTemp);
client.Disconnect();
}
catch (ImapException ex)
{
MessageBox.Show(ex.ToString());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set security mode
client.SecurityOptions = SecurityOptions.SSLImplicit;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create a POP3 client
Aspose.Email.Pop3.Pop3Client client;
client = new Aspose.Email.Pop3.Pop3Client();
// Basic settings (required)
client.Host = "pop3.youdomain.com";
client.Username = "username";
client.Password = "psw";
try
{
// Retrieve first message in MailMessage format directly
Aspose.Email.Mail.MailMessage msg;
msg = client.FetchMessage(1);
txtFrom.Text = msg.From.ToString();
txtSubject.Text = msg.Subject.ToString();
txtBody.Text = msg.HtmlBody.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try
{
// Disconnect from POP3 server
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set implicit security mode
client.SecurityOptions = Aspose.Email.SecurityOptions.SSLImplicit;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
RecurrencePattern recurrencePattern = new RecurrencePattern();
recurrencePattern.StartDate = new DateTime(1997, 9, 10, 9, 0, 0);
RecurrenceRule rule = recurrencePattern.RRules.Add();
rule.Frequency = Frequency.Monthly;
rule.Count = 20;
rule.Interval = 18;
rule.ByMonthDay.Add(new int[] { 10, 11, 12, 13, 14, 15 });
DateCollection expectedDates = recurrencePattern.GenerateOccurrences(20);
Console.WriteLine("expectedDates.Count = " + expectedDates.Count);
foreach (DateTime date in expectedDates)
{
Console.WriteLine("DateTime = " + date);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
try
{
// Get the message ID of the selected row
string strMessageID = dgMeetings.SelectedRows[0].Cells["MessageID"].Value.ToString();
// Get the message and calendar information from the database get the attendee information
string strSQLGetAttendees = "SELECT * FROM Attendent WHERE MessageID = '" + strMessageID + "' ";
// Get the attendee information in reader
SqlDataReader rdAttendees = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, strSQLGetAttendees, null);
// Create a MailAddressCollection from the attendees found in the database
MailAddressCollection attendees = new MailAddressCollection();
while (rdAttendees.Read())
{
attendees.Add(new MailAddress(rdAttendees["EmailAddress"].ToString(), rdAttendees["DisplayName"].ToString()));
}
// Get message and calendar information
string strSQLGetMessage = "SELECT * FROM [Message] WHERE MessageID = '" + strMessageID + "' ";
// Get the reader for the above query
SqlDataReader rdMessage = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, strSQLGetMessage, null);
rdMessage.Read();
// Create the Calendar object from the database information
Appointment app = new Appointment(rdMessage["CalLocation"].ToString(), rdMessage["CalSummary"].ToString(), rdMessage["CalDescription"].ToString(),
DateTime.Parse(rdMessage["CalStartTime"].ToString()), DateTime.Parse(rdMessage["CalEndTime"].ToString()), new MailAddress(rdMessage["FromEmailAddress"].ToString(), rdMessage["FromDisplayName"].ToString()), attendees);
// Create message and Set from and to addresses and Add the cancel meeting request
MailMessage msg = new MailMessage();
msg.From = new MailAddress(rdMessage["FromEmailAddress"].ToString(), "");
msg.To = attendees;
msg.Subject = "Cencel meeting";
msg.AddAlternateView(app.CancelAppointment());
SmtpClient smtp = new SmtpClient("mail.domain.com", "user", "password");
smtp.Send(msg);
MessageBox.Show("cancellation request successfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Set conditions
ImapQueryBuilder builder = new ImapQueryBuilder();
builder.Subject.Contains("Newsletter",true);
builder.InternalDate.On(DateTime.Now);
MailQuery query = builder.GetQuery();
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage message = new MailMessage("Sender Name <sender@from.com>", "Kyle Huang <kyle@to.com>");
// A To address with a friendly name can also be specified like this
// message.To.Add(new MailAddress("kyle@to.com", "Kyle Huang"));
// Specify Cc and Bcc email address along with a friendly name
message.CC.Add(new MailAddress("guangzhou@cc.com", "Guangzhou Team"));
message.Bcc.Add(new MailAddress("ahaq@bcc.com", "Ammad ulHaq "));
// Create an instance of SmtpClient Class and Specify your mailing host server, Username, Password, Port
SmtpClient client = new SmtpClient();
client.Host = "smtp.server.com";
client.Username = "Username";
client.Password = "Password";
client.Port = 25;
try
{
// Client.Send will send this message
client.Send(message);
Console.WriteLine("Message sent");
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an object of type Pop3MailboxInfo and Get the mailbox information, Check number of messages, and Check mailbox size
Aspose.Email.Pop3.Pop3MailboxInfo info;
info = client.GetMailboxInfo();
Console.WriteLine(info.MessageCount);
Console.Write(info.OccupiedSize + " bytes");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Get the list of messages in the mailbox and Iterate through the messages
Aspose.Email.Pop3.Pop3MessageInfoCollection infos = client.ListMessages();
foreach (Aspose.Email.Pop3.Pop3MessageInfo info in infos)
{
Console.Write("ID:" + info.UniqueId);
Console.Write("Index number:" + info.SequenceNumber);
Console.Write("Subject:" + info.Subject);
Console.Write("Size:" + info.Size);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Emails from specific host, get all emails that arrived before today and all emails that arrived since 7 days ago
builder.From.Contains("SpecificHost.com");
builder.InternalDate.Before(DateTime.Now);
builder.InternalDate.Since(DateTime.Now.AddDays(-7));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Get emails sent to specific recipient
builder.To.Contains("recipient");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Specify OR condition
builder.Or(builder.Subject.Contains("test"), builder.From.Contains("noreply@host.com"));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
Aspose.Email.Mail.SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Username = "user@gmail.com";
client.Password = "pwd";
client.Port = 587;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
Aspose.Email.Imap.ImapClient client = new Aspose.Email.Imap.ImapClient("imap.domain.com", 993, "user@domain.com", "pwd");
// Set the security mode to implicit
client.SecurityOptions = SecurityOptions.SSLImplicit;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect to the Gmail server
Aspose.Email.Imap.ImapClient imap = new Aspose.Email.Imap.ImapClient("imap.gmail.com", 993, "user@gmail.com", "pwd");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory and load the MSG file using Aspose.Email for .NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage msg = MailMessage.Load(dataDir + "test-message.msg", new MsgLoadOptions());
// Convert MSG to MHTML and save to stream
MemoryStream msgStream = new MemoryStream();
msg.Save(msgStream, SaveOptions.DefaultMhtml);
msgStream.Position = 0;
// Load the MHTML stream using Aspose.Words for .NET and Save the document as TIFF image
Document msgDocument = new Document(msgStream);
msgDocument.Save(dataDir+ "Outlook-Aspose_out.tif", SaveFormat.Tiff);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
imap.CreateFolder("NewFolder");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Delete a folder and Rename a folder
imap.DeleteFolder("foldername");
imap.RenameFolder("foldername", "newfoldername");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Connect to the POP3 mail server and check messages.
Aspose.Email.Pop3.Pop3Client pop3Client = new Aspose.Email.Pop3.Pop3Client("pop3mailserver", "username", "password");
pop3Client.Connect(true);
// List all the messages
Aspose.Email.Pop3.Pop3MessageInfoCollection msgList = pop3Client.ListMessages();
foreach (Aspose.Email.Pop3.Pop3MessageInfo msgInfo in msgList)
{
// Get the POP3 message's unique ID
string strUniqueID = msgInfo.UniqueId;
// Search your local database or data store on the unique ID. If a match is found, that means it's already downloaded. Otherwise download and save it.
if (SearchPop3MsgInLocalDB(strUniqueID) == true)
{
// The message is already in the database. Nothing to do with this message. Go to next message.
}
else
{
// Save the message
SavePop3MsgInLocalDB(msgInfo);
}
}
private void SavePop3MsgInLocalDB(Aspose.Email.Pop3.Pop3MessageInfo msgInfo)
{
// Open the database connection according to your database. Use public properties (for example msgInfo.Subject) and store in database,
// for example, " INSERT INTO POP3Mails (UniqueID, Subject) VALUES ('" + msgInfo.UniqueID + "' , '" + msgInfo.Subject + "') and Run the query to store in database.
}
private bool SearchPop3MsgInLocalDB(string strUniqueID)
{
// Open the database connection according to your database. Use strUniqueID in the search query to find existing records,
// for example, " SELECT COUNT(*) FROM POP3Mails WHERE UniqueID = '" + strUniqueID + "' Run the query, return true if count == 1. Return false if count == 0.
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
//Create a loop to display the no. of attachments present in email message
foreach (Attachment attachment in message.Attachments)
{
// Save your attachments here and display the the attachment file name
attachment.Save("filename");
Console.WriteLine(attachment.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Export an EML file
msg.Save(@"e:\test.eml", SaveOptions.DefaultEml);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance of MailMessage class
MailMessage message = new MailMessage { From = "sender@sender.com" };
message.To.Add("receiver@gmail.com");
// Load an attachment
Attachment attachment = new Attachment(dataDir + "1.txt");
// Add Multiple Attachment in instance of MailMessage class and Save message to disk
message.Attachments.Add(attachment);
message.AddAttachment(new Attachment(dataDir + "1.jpg"));
message.AddAttachment(new Attachment(dataDir + "1.doc"));
message.AddAttachment(new Attachment(dataDir + "1.rar"));
message.AddAttachment(new Attachment(dataDir + "1.pdf"));
message.Save(dataDir + "outputAttachments_out.msg", SaveOptions.DefaultMsgUnicode);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance of MailMessage class
MailMessage message = new MailMessage {From = "sender@sender.com"};
message.To.Add("receiver@gmail.com");
// Load an attachment
Attachment attachment = new Attachment(dataDir + "1.txt");
// Add Multiple Attachment in instance of MailMessage class and Save message to disk
message.Attachments.Add(attachment);
message.AddAttachment(new Attachment(dataDir + "1.jpg"));
message.AddAttachment(new Attachment(dataDir + "1.doc"));
message.AddAttachment(new Attachment(dataDir + "1.rar"));
message.AddAttachment(new Attachment(dataDir + "1.pdf"));
message.Save(dataDir + "outputAttachments_out.msg", SaveOptions.DefaultMsgUnicode);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string fileName = "MainMessage.eml";
string attachName = "s.png";
string outFileName = "test.eml";
MailMessage mailMessage = MailMessage.Load(fileName);
mailMessage.Attachments.Add(new Attachment(File.OpenRead(attachName), "s.png", "image/png"));
mailMessage.Save(outFileName, FileCompatibilityMode.PreserveTnefAttachments);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string fileName = "tnefEml1.eml";
string attachName = "Untitled.jpg";
string outFileName = "test_out.eml";
MailMessage mailMessage = MailMessage.Load(dataDir + fileName);
mailMessage.Attachments.Add(new Attachment(File.OpenRead(dataDir + attachName), "Untitled.jpg", "image/jpg"));
EmlSaveOptions eo = new EmlSaveOptions(MailMessageSaveType.EmlFormat);
eo.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;
mailMessage.Save(dataDir + outFileName, eo);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
AlternateView alternate;
// Creates AlternateView to view an email message using the content specified in the //string
alternate = AlternateView.CreateAlternateViewFromString("Alternate Text");
// Adding alternate text
message.AlternateViews.Add(alternate);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of SmtpClient class
SmtpClient client = new SmtpClient();
client.AuthenticationMethod = SmtpAuthentication.Auto;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string hamFolder = RunExamples.GetDataDir_Email() + "/hamFolder";
string spamFolder = RunExamples.GetDataDir_Email() + "/Spam";
string testFolder = RunExamples.GetDataDir_Email();
string dataBaseFile = RunExamples.GetDataDir_Email() + "SpamFilterDatabase.txt";
TeachAndCreateDatabase(hamFolder, spamFolder, dataBaseFile);
string[] testFiles = Directory.GetFiles(testFolder, "*.eml");
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile);
foreach (string file in testFiles)
{
MailMessage msg = MailMessage.Load(file);
Console.WriteLine(msg.Subject);
double probability = analyzer.Test(msg);
PrintResult(probability);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string hamFolder = RunExamples.GetDataDir_Email() + "/hamFolder";
string spamFolder = RunExamples.GetDataDir_Email() + "/Spam";
string testFolder = RunExamples.GetDataDir_Email();
string dataBaseFile = RunExamples.GetDataDir_Email() + "SpamFilterDatabase.txt";
TeachAndCreateDatabase(hamFolder, spamFolder, dataBaseFile);
string[] testFiles = Directory.GetFiles(testFolder, "*.eml");
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile);
foreach (string file in testFiles)
{
MailMessage msg = MailMessage.Load(file);
Console.WriteLine(msg.Subject);
double probability = analyzer.Test(msg);
PrintResult(probability);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
message.BodyEncoding = Encoding.ASCII;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage message = MailMessage.Load(dataDir + "test.eml");
// A To address with a friendly name can also be specified like this
message.To.Add(new MailAddress("kyle@to.com", "Kyle Huang"));
// Specify Cc and Bcc email address along with a friendly name
message.CC.Add(new MailAddress("guangzhou@cc.com", "Guangzhou Team"));
message.Bcc.Add(new MailAddress("ahaq@bcc.com", "Ammad ulHaq "));
message.Save(dataDir + "MessageWithFrienlyName_out.eml", SaveOptions.DefaultEml);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
MhtSaveOptions options = SaveOptions.DefaultMhtml;
int cssInsertPos = options.CssStyles.LastIndexOf("</style>");
options.CssStyles = options.CssStyles.Insert(cssInsertPos,
".PlainText{" +
" font-family: sans-serif;" +
"}"
);
eml.Save("message.mhtml", options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string fileName = RunExamples.GetDataDir_Email() + "failed1.msg";
MailMessage mail = MailMessage.Load(fileName);
BounceResult result = mail.CheckBounced();
Console.WriteLine(fileName);
Console.WriteLine("IsBounced : " + result.IsBounced);
Console.WriteLine("Action : " + result.Action);
Console.WriteLine("Recipient : " + result.Recipient);
Console.WriteLine();
Console.WriteLine("Reason : " + result.Reason);
Console.WriteLine("Status : " + result.Status);
Console.WriteLine("OriginalMessage ToAddress 1: " + result.OriginalMessage.To[0].Address);
Console.WriteLine();
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage mailMessageOrig = MailMessage.Load(Path.Combine(dataDir, "Message.msg"), new MsgLoadOptions());
X509Certificate2 publicCert = new X509Certificate2(publicCertFile);
X509Certificate2 privateCert = new X509Certificate2(privateCertFile, "anothertestaccount");
Console.WriteLine("Message is encrypted: {0}" , mailMessageOrig.IsEncrypted);
MailMessage mailMessage = mailMessageOrig.Encrypt(publicCert);
Console.WriteLine("Message is encrypted: {0}", mailMessage.IsEncrypted);
mailMessage = mailMessage.Decrypt(privateCert);
Console.WriteLine("Message is encrypted: {0}", mailMessage.IsEncrypted);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
message.ConfirmRead = true;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(Path.Combine(dataDir, "Message.eml"));
// Save as mht with header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to outpu without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
eml.Save(Path.Combine(dataDir, "outMessage_out.mht"), mhtSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
mhtSaveOptions.SkipInlineImages = true;
eml.Save(Path.Combine(dataDir, "EmlToMhtmlWithoutInlineImages_out.mht"), mhtSaveOptions);
// For complete examples and data files, please go to https:// github.com/aspose-email/Aspose.Email-for-.NET
string username = "username";
string email = "email@gmail.com";
string password = "password";
string clientId = "clientid";
string clientSecret = "client secret";
string refresh_token = "refresh token";
// The refresh_token is to be used in below.
GoogleTestUser user = new GoogleTestUser(username, email, password, clientId, clientSecret, refresh_token);
using (IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken))
{
Contact[] contacts = client.GetAllContacts();
foreach (Contact contact in contacts)
Console.WriteLine(contact.DisplayName + ", " + contact.EmailAddresses[0]);
// Fetch contacts from a specific group
FeedEntryCollection groups = client.FetchAllGroups();
GmailContactGroup group = null;
foreach (GmailContactGroup g in groups)
switch (g.Title)
{
case "TestGroup": group = g;
break;
}
// Retrieve contacts from the Group
if (group != null)
{
Contact[] contacts2 = client.GetContactsFromGroup(group);
foreach (Contact con in contacts2)
Console.WriteLine(con.DisplayName + "," + con.EmailAddresses[0].ToString());
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set subject of the message, Html body and sender information
message.Subject = "New message created by Aspose.Email for .NET";
message.HtmlBody = "<b>This line is in bold.</b> <br/> <br/>" + "<font color=blue>This line is in blue color</font>";
message.From = new MailAddress("from@domain.com", "Sender Name", false);
// Add TO recipients and Add CC recipients
message.To.Add(new MailAddress("to1@domain.com", "Recipient 1", false));
message.To.Add(new MailAddress("to2@domain.com", "Recipient 2", false));
message.CC.Add(new MailAddress("cc1@domain.com", "Recipient 3", false));
message.CC.Add(new MailAddress("cc2@domain.com", "Recipient 4", false));
// Save message in EML, EMLX, MSG and MHTML formats
message.Save(dataDir + "CreateNewMailMessage_out.eml", SaveOptions.DefaultEml);
message.Save(dataDir + "CreateNewMailMessage_out.emlx", SaveOptions.CreateSaveOptions(MailMessageSaveType.EmlxFormat));
message.Save(dataDir + "CreateNewMailMessage_out.msg", SaveOptions.DefaultMsgUnicode);
message.Save(dataDir + "CreateNewMailMessage_out.mhtml", SaveOptions.DefaultMhtml);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessageLoadOptions options = new MailMessageLoadOptions();
options.MessageFormat = MessageFormat.Msg;
// The PreserveTnefAttachments option with MessageFormat.Msg will create the TNEF eml.
options.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;
MailMessage eml = MailMessage.Load(emlFileName, options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MapiMessage mapiMsg = MapiMessage.FromFile(dataDir + "Message.msg");
MailConversionOptions mco = new MailConversionOptions();
mco.ConvertAsTnef = true;
MailMessage message = mapiMsg.ToMailMessage(mco);
// For complete examples and data files, please go to https:// github.com/aspose-email/Aspose.Email-for-.NET
string username = "newcustomeroffnet";
string email = "newcustomeroffnet@gmail.com";
string password = "visual2010";
string clientId = "633643385868-v64nsvkmh5ca2dlhkroo8941ne92onov.apps.googleusercontent.com";
string clientSecret = "UQ26EXvvo8L12TNhtLtYbHVO";
string refresh_token = "1/yord7s4aqV8t7S_vT9IqlBO60eIE-hY0WHLfqQ9zOCQ";
// The refresh_token is to be used in below.
GoogleTestUser user = new GoogleTestUser(username, email, password, clientId, clientSecret,refresh_token);
// Gmail Client
IGmailClient client = Aspose.Email.Google.GmailClient.GetInstance(user.ClientId, user.ClientSecret, user.RefreshToken, user.EMail);
// Create a Contact
Contact contact = new Contact();
contact.Prefix = "Prefix";
contact.GivenName = "GivenName";
contact.Surname = "Surname";
contact.MiddleName = "MiddleName";
contact.DisplayName = "Test User 1";
contact.Suffix = "Suffix";
contact.JobTitle = "JobTitle";
contact.DepartmentName = "DepartmentName";
contact.CompanyName = "CompanyName";
contact.Profession = "Profession";
contact.Notes = "Notes";
PostalAddress address = new PostalAddress();
address.Category = PostalAddressCategory.Work;
address.Address = "Address";
address.Street = "Street";
address.PostOfficeBox = "PostOfficeBox";
address.City = "City";
address.StateOrProvince = "StateOrProvince";
address.PostalCode = "PostalCode";
address.Country = "Country";
contact.PhysicalAddresses.Add(address);
PhoneNumber pnWork = new PhoneNumber();
pnWork.Number = "323423423423";
pnWork.Category = PhoneNumberCategory.Work;
contact.PhoneNumbers.Add(pnWork);
PhoneNumber pnHome = new PhoneNumber();
pnHome.Number = "323423423423";
pnHome.Category = PhoneNumberCategory.Home;
contact.PhoneNumbers.Add(pnHome);
PhoneNumber pnMobile = new PhoneNumber();
pnMobile.Number = "323423423423";
pnMobile.Category = PhoneNumberCategory.Mobile;
contact.PhoneNumbers.Add(pnMobile);
contact.Urls.Blog = "Blog.ru";
contact.Urls.BusinessHomePage = "BusinessHomePage.ru";
contact.Urls.HomePage = "HomePage.ru";
contact.Urls.Profile = "Profile.ru";
contact.Events.Birthday = DateTime.Now.AddYears(-30);
contact.Events.Anniversary = DateTime.Now.AddYears(-10);
contact.InstantMessengers.AIM = "AIM";
contact.InstantMessengers.GoogleTalk = "GoogleTalk";
contact.InstantMessengers.ICQ = "ICQ";
contact.InstantMessengers.Jabber = "Jabber";
contact.InstantMessengers.MSN = "MSN";
contact.InstantMessengers.QQ = "QQ";
contact.InstantMessengers.Skype = "Skype";
contact.InstantMessengers.Yahoo = "Yahoo";
contact.AssociatedPersons.Spouse = "Spouse";
contact.AssociatedPersons.Sister = "Sister";
contact.AssociatedPersons.Relative = "Relative";
contact.AssociatedPersons.ReferredBy = "ReferredBy";
contact.AssociatedPersons.Partner = "Partner";
contact.AssociatedPersons.Parent = "Parent";
contact.AssociatedPersons.Mother = "Mother";
contact.AssociatedPersons.Manager = "Manager";
// Email Address
EmailAddress eAddress = new EmailAddress();
eAddress.Address = "email@gmail.com";
contact.EmailAddresses.Add(eAddress);
string contactUri = client.CreateContact(contact);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MapiMessage msg = MapiMessage.FromFile(dataDir + "Message.msg");
MailConversionOptions options = new MailConversionOptions {ConvertAsTnef = true};
MailMessage mail = msg.ToMailMessage(options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance MailMessage class
MailMessage mailMessage = new MailMessage();
// Specify ReplyTo, From, To field, Cc and Bcc Addresses
mailMessage.ReplyToList.Add("reply@reply.com");
mailMessage.From = "sender@sender.com";
mailMessage.To.Add("receiver1@receiver.com");
mailMessage.CC.Add("receiver2@receiver.com");
mailMessage.Bcc.Add("receiver3@receiver.com");
// Specify Date, Message subject, XMailer, Secret Header, Save message to disc
mailMessage.Subject = "test mail";
mailMessage.Date = new System.DateTime(2006, 3, 6);
mailMessage.XMailer = "Aspose.Email";
mailMessage.Headers.Add_("secret-header", "mystery");
mailMessage.Save("MessageHeaders.msg", SaveOptions.DefaultMsg);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Add by SMTP server in delivery emails
Received: from ip-123.56.99.216.dsl-cust.ca.inter.net ([216.99.56.123]) by Aspose.secureserver.net with MailEnable ESMTP; Thu, 22 Feb 2007 13:58:57 -0700
// Add by SMTP server in delivery emails
Return-Path: <xyz@oikoscucine.it>
// Add by SMTP server in delivery emails
Received: from 195.120.225.20 (HELO mail.oikoscucine.it)
by aspose.com with esmtp (:1CYY+<LA*- *1WK@)
id Q8,/O/-.N83@7-9M
for abc@aspose.com; Thu, 22 Feb 2007 20:58:51 +0300
From: "XYZ" <xyz@oikoscucine.it>
To: <abc@aspose.com>
Subject: For ABC
// Date will set the Date field, outlook will show this as
Date: Thu, 22 Feb 2007 20:58:51 +0300
Message-ID: <01c756c4$41b554d0$6c822ecf@dishonestyinsufferably>
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_NextPart_000_0006_01C7569A.58DF4CD0"
X-Mailer: Microsoft Office Outlook, Build 11.0.5510
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1106
Thread-Index: Aca6Q:=ES0M(9-=(<.<1.<Q9@QE6CD==
X-Read: 1
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Detect file format and Gets the detected load format
FileFormatInfo info = FileFormatUtil.DetectFileFormat(dataDir + "message.msg");
Console.WriteLine("The message format is: " + info.FileFormatType);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage mail = MailMessage.Load(dataDir + "tnefEml1.eml");
bool isTnef = mail.OriginalIsTnef;
Console.WriteLine("Is input EML originally TNEF? {0}", isTnef.ToString());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email() + "Message.eml";
MailMessage mail = MailMessage.Load(dataDir);
bool isTnef = mail.OriginalIsTnef;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email() + "EmailWithAttandEmbedded.eml";
MailMessage eml = MailMessage.Load(dataDir);
if (eml.Attachments[0].IsEmbeddedMessage)
Console.WriteLine("Attachment is an embedded message.");
else
Console.WriteLine("Attachment is not an embedded message.");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create a loop to display the no. of attachments present in email message
foreach (Attachment attachment in message.Attachments)
{
// Display the the attachment file name
Console.WriteLine(attachment.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Declare message as MailMessage instance
MailMessage message = new MailMessage("Sender <sender@from.com>", "Recipient <recipient@to.com>");
// Specify the recipients mail addresses
message.To.Add("receiver1@receiver.com");
message.To.Add("receiver2@receiver.com");
message.To.Add("receiver3@receiver.com");
message.To.Add("receiver4@receiver.com");
// Specifying CC and BCC Addresses
message.CC.Add("CC1@receiver.com");
message.CC.Add("CC2@receiver.com");
message.Bcc.Add("Bcc1@receiver.com");
message.Bcc.Add("Bcc2@receiver.com");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create MailMessage instance by loading an Eml file
MailMessage message = MailMessage.Load(dataDir + "test.eml", new EmlLoadOptions());
// Gets the sender info, recipient info, Subject, htmlbody and textbody
Console.Write("From:");
Console.WriteLine(message.From);
Console.Write("To:");
Console.WriteLine(message.To);
Console.Write("Subject:");
Console.WriteLine(message.Subject);
Console.WriteLine("HtmlBody:");
Console.WriteLine(message.HtmlBody);
Console.WriteLine("TextBody");
Console.WriteLine(message.Body);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage message = new MailMessage("Sender <sender@from.com>", "Recipient <recipient@to.com>");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string ical = @"BEGIN:VCALENDAR
METHOD:PUBLISH
PRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN
VERSION:2.0
BEGIN:VEVENT
ATTENDEE;CN=test@gmail.com:mailto:test@gmail.com
DTSTART:20130220T171439
DTEND:20130220T174439
DTSTAMP:20130220T161439Z
END:VEVENT
END:VCALENDAR";
string sender = "test@gmail.com";
string recipient = "test@email.com";
MailMessage message = new MailMessage(sender, recipient, string.Empty, string.Empty);
AlternateView av = AlternateView.CreateAlternateViewFromString(ical, new ContentType("text/calendar"));
message.AlternateViews.Add(av);
MapiMessage msg = MapiMessage.FromMailMessage(message);
msg.Save(dataDir + "draft_out.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string dstDraft = dataDir + "appointment-draft_out.msg";
string sender = "test@gmail.com";
string recipient = "test@email.com";
MailMessage message = new MailMessage(sender, recipient, string.Empty, string.Empty);
Appointment app = new Appointment(string.Empty, DateTime.Now, DateTime.Now, sender, recipient)
{
MethodType = AppointmentMethodType.Publish
};
message.AddAlternateView(app.RequestApointment());
MapiMessage msg = MapiMessage.FromMailMessage(message);
// Save the appointment as draft.
msg.Save(dstDraft);
Console.WriteLine(Environment.NewLine + "Draft saved at " + dstDraft);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
EmailValidator ev = new EmailValidator();
ValidationResult result;
try
{
ev.Validate(txtEmailAddr.Text, out result);
if (result.ReturnCode == ValidationResponseCode.ValidationSuccess)
{
lblResult.Text = "The email address is valid.";
}
else
{
lblResult.Text = "The mail address is invalid,return code is : " + result.ReturnCode + ".";
}
}
catch (Exception ex)
{
lblResult.Text += "<br>" + ex.Message;
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string dstEmail = dataDir + "EmbeddedImage.msg";
// Create an instance of the MailMessage class and Set the addresses and Set the content
MailMessage mail = new MailMessage();
mail.From = new MailAddress("test001@gmail.com");
mail.To.Add("test001@gmail.com");
mail.Subject = "This is an email";
// Create the plain text part It is viewable by those clients that don't support HTML
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content", null, "text/plain");
/* Create the HTML part.To embed images, we need to use the prefix 'cid' in the img src value.
The cid value will map to the Content-Id of a Linked resource. Thus <img src='cid:barcode'> will map to a LinkedResource with a ContentId of //'barcode'. */
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:barcode>", null, "text/html");
// Create the LinkedResource (embedded image) and Add the LinkedResource to the appropriate view
LinkedResource barcode = new LinkedResource(dataDir + "1.jpg", MediaTypeNames.Image.Jpeg)
{
ContentId = "barcode"
};
mail.LinkedResources.Add(barcode);
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
mail.Save(dataDir + "EmbeddedImage_out.msg", SaveOptions.DefaultMsgUnicode);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string publicCertFile = dataDir + "MartinCertificate.cer";
string privateCertFile = dataDir + "MartinCertificate.pfx";
X509Certificate2 publicCert = new X509Certificate2(publicCertFile);
X509Certificate2 privateCert = new X509Certificate2(privateCertFile, "anothertestaccount");
// Create a message
MailMessage msg = new MailMessage("atneostthaecrcount@gmail.com", "atneostthaecrcount@gmail.com", "Test subject", "Test Body");
// Encrypt the message
MailMessage eMsg = msg.Encrypt(publicCert);
if (eMsg.IsEncrypted == true)
Console.WriteLine("Its encrypted");
else
Console.WriteLine("Its NOT encrypted");
// Decrypt the message
MailMessage dMsg = eMsg.Decrypt(privateCert);
if (dMsg.IsEncrypted == true)
Console.WriteLine("Its encrypted");
else
Console.WriteLine("Its NOT encrypted");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage msg = MailMessage.Load(dataDir + "Message.eml");
msg.Save(dataDir + "ExporttoEml_out.eml", SaveOptions.DefaultEml);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
// Set the local time for message date.
eml.TimeZoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
// or set custom time zone offset for message date (-0800)
// eml.TimeZoneOffset = new TimeSpan(-8,0,0);
// The dates will be rendered by local system time zone.
MhtSaveOptions so = new MhtSaveOptions();
so.MhtFormatOptions = MhtFormatOptions.WriteHeader;
eml.Save(dataDir + "ExportEmailToMHTWithCustomTimezone_out.mhtml", so);
// For complete examples and data files, please go to https:// github.com/aspose-email/Aspose.Email-for-.NET
// Export an EML file
message.Save(@"e:\test.eml", SaveOptions.DefaultEml);
// For complete examples and data files, please go to https:// github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(fileName);
// Set the local time for message date.
eml.TimeZoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
// or set custom time zone offset for message date (-0800)
// eml.TimeZoneOffset = new TimeSpan(-8,0,0);
// The dates will be rendered by local system time zone.
eml.Save(outFileName, MessageFormat.Mht, MailMessageSaveOptions.WriteHeaderToMht);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(fileName);
// Set the local time for message date.
eml.TimeZoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
// The dates will be rendered by local system time zone.
eml.Save(outFileName, MessageFormat.Mht, MailMessageSaveOptions.WriteHeaderToMht);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance of MailMessage and load an email file
MailMessage mailMsg = MailMessage.Load(dataDir + "EmailWithAttandEmbedded.eml");
// Extract Attachments from the message
foreach (Attachment attachment in mailMsg.Attachments)
{
// To display the the attachment file name
Console.WriteLine(attachment.Name);
// Save the attachment to disc
attachment.Save(dataDir + attachment.Name);
// You can also save the attachment to memory stream
MemoryStream ms = new MemoryStream();
attachment.Save(ms);
}
// Extract Inline images from the message
foreach (LinkedResource lr in mailMsg.LinkedResources)
{
Console.WriteLine(lr.ContentType.Name);
lr.Save(dataDir + lr.ContentType.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance of MailMessage and load an email file
MailMessage mailMsg = MailMessage.Load(dataDir + "Message.msg", new MsgLoadOptions());
foreach (Attachment attachment in mailMsg.Attachments)
{
// To display the the attachment file name
attachment.Save(dataDir + "MessageEmbedded_out.msg");
Console.WriteLine(attachment.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create MailMessage instance by loading an EML file
MailMessage mailMessage = MailMessage.Load("Sample.eml", MailMessageLoadOptions.DefaultEml);
Console.WriteLine("\n\nheaders:\n\n");
// Print out all the headers
foreach (String header in message.Headers)
{
Console.WriteLine(header);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage message;
// Create MailMessage instance by loading an EML file
message = MailMessage.Load(dataDir + "email-headers.eml", new EmlLoadOptions());
Console.WriteLine("\n\nheaders:\n\n");
// Print out all the headers
int index = 0;
foreach (String header in message.Headers)
{
Console.Write(header + " - ");
Console.WriteLine(message.Headers.Get(index++));
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public static void ExtractInlineAttachments(string dataDir)
{
MapiMessage message = MapiMessage.FromFile(dataDir + "MSG file with RTF Formatting.msg");
MapiAttachmentCollection attachments = message.Attachments;
foreach (MapiAttachment attachment in attachments)
{
if(IsAttachmentInline(attachment))
{
try
{
SaveAttachment(attachment, new Guid().ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
static bool IsAttachmentInline(MapiAttachment attachment)
{
foreach (MapiProperty property in attachment.ObjectData.Properties.Values)
{
if (property.Name == "\x0003ObjInfo")
{
ushort odtPersist1 = BitConverter.ToUInt16(property.Data, 0);
return (odtPersist1 & (1 << (7 - 1))) == 0;
}
}
return false;
}
static void SaveAttachment(MapiAttachment attachment, string fileName)
{
foreach (MapiProperty property in attachment.ObjectData.Properties.Values)
{
if (property.Name == "Package")
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(property.Data, 0, property.Data.Length);
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string mhtFileName = dataDir + "Message.mhtml";
MailMessage message = MailMessage.Load(dataDir + "Message.eml");
string encodedPageHeader = @"<div><div class=3D'page=Header'>&quot;Panditharatne, Mithra&quot; &lt;mithra=2Epanditharatne@cibc==2Ecom&gt;<hr/></div>";
MhtMessageFormatter mailFormatter = new MhtMessageFormatter();
MhtFormatOptions options = MhtFormatOptions.WriteCompleteEmailAddress | MhtFormatOptions.WriteHeader;
mailFormatter.Format(message);
message.Save(mhtFileName, Aspose.Email.Mail.SaveOptions.DefaultMhtml);
if (File.ReadAllText(mhtFileName).Contains(encodedPageHeader))
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
//Assert.True(File.ReadAllText(mhtFileName).Contains(encodedPageHeader));
options = options | MhtFormatOptions.HideExtraPrintHeader;
mailFormatter.Format(message);
message.Save(mhtFileName, Aspose.Email.Mail.SaveOptions.DefaultMhtml);
if (File.ReadAllText(mhtFileName).Contains(encodedPageHeader))
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
message.Date = DateTime.Now;
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage mailMessage = MailMessage.Load(dataDir + "emlWithHeaders.eml");
string decodedValue = mailMessage.Headers.GetDecodedValue("Thread-Topic");
Console.WriteLine(decodedValue);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage mailMessage = MailMessage.Load("mail-8820003991514049235.EML");
string decodedValue = mailMessage.Headers.GetDecodedValue("Thread-Topic");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string fileName = RunExamples.GetDataDir_Email() + "failed1.msg";
MailMessage mail = MailMessage.Load(fileName);
BounceResult result = mail.CheckBounced();
Console.WriteLine(fileName);
Console.WriteLine("IsBounced : " + result.IsBounced);
Console.WriteLine("Action : " + result.Action);
Console.WriteLine("Recipient : " + result.Recipient);
Console.WriteLine();
Console.WriteLine("Reason : " + result.Reason);
Console.WriteLine("Status : " + result.Status);
Console.WriteLine("OriginalMessage ToAddress 1: " + result.OriginalMessage.To[0].Address);
Console.WriteLine();
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public static void Run()
{
string dataDir = RunExamples.GetDataDir_Email();
var message = MapiMessage.FromFile(dataDir + "RemoveAttachments.msg");
var attachments = message.Attachments;
var count = attachments.Count;
Console.WriteLine("Total attachments " + count);
for (int i = 0; i < attachments.Count; i++)
{
var attachment = attachments[i];
if (IsInlineAttachment(attachment, message))
{
Console.WriteLine(attachment.LongFileName + " is inline attachment");
}
else
{
Console.WriteLine(attachment.LongFileName + " is regular attachment");
}
}
}
public static bool IsInlineAttachment(MapiAttachment att, MapiMessage msg)
{
switch (msg.BodyType)
{
case BodyContentType.PlainText:
// ignore indications for plain text messages
return false;
case BodyContentType.Html:
// check the PidTagAttachFlags property
if (att.Properties.ContainsKey(0x37140003))
{
long? attachFlagsValue = att.GetPropertyLong(0x37140003);
if (attachFlagsValue != null && (attachFlagsValue & 0x00000004) == 0x00000004)
{
// check PidTagAttachContentId property
if (att.Properties.ContainsKey(MapiPropertyTag.PR_ATTACH_CONTENT_ID) ||
att.Properties.ContainsKey(MapiPropertyTag.PR_ATTACH_CONTENT_ID_W))
{
string contentId = att.Properties.ContainsKey(MapiPropertyTag.PR_ATTACH_CONTENT_ID)
? att.Properties[MapiPropertyTag.PR_ATTACH_CONTENT_ID].GetString()
: att.Properties[MapiPropertyTag.PR_ATTACH_CONTENT_ID_W].GetString();
if (msg.BodyHtml.Contains(contentId))
{
return true;
}
}
// check PidTagAttachContentLocation property
if (att.Properties.ContainsKey(0x3713001E) ||
att.Properties.ContainsKey(0x3713001F))
{
return true;
}
}
else if ((att.Properties.ContainsKey(0x3716001F) && att.GetPropertyString(0x3716001F) == "inline")
|| (att.Properties.ContainsKey(0x3716001E) && att.GetPropertyString(0x3716001E) == "inline"))
{
return true;
}
}
else if ((att.Properties.ContainsKey(0x3716001F) && att.GetPropertyString(0x3716001F) == "inline")
|| (att.Properties.ContainsKey(0x3716001E) && att.GetPropertyString(0x3716001E) == "inline"))
{
return true;
}
return false;
case BodyContentType.Rtf:
// If the body is RTF, then all OLE attachments are inline attachments.
// OLE attachments have 0x00000006 for the value of the PidTagAttachMethod property
if (att.Properties.ContainsKey(MapiPropertyTag.PR_ATTACH_METHOD))
{
return att.GetPropertyLong(MapiPropertyTag.PR_ATTACH_METHOD) == 0x00000006;
}
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Insert Header at Specific Location
MailMessage emailMessage = MailMessage.Load(fileName);
emailMessage.Headers.Insert("Received", "Value");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage mailMessage = MailMessage.Load(dataDir + "Attachments.eml");
mailMessage.Save(dataDir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.DefaultEml);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of SmtpClient class and load SMTP Authentication settings from Config file
SmtpClient client = new SmtpClient(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Data directory for reading and writing files
string dataDir = RunExamples.GetDataDir_Email();
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
// Save the Email message to disk in ASCII format and Unicode format
eml.Save(dataDir + "AnEmail_out.msg", SaveOptions.DefaultMsgUnicode);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Load Eml, html, mhtml, msg and dat file
MailMessage mailMessage = MailMessage.Load(dataDir + "Message.eml", new EmlLoadOptions());
MailMessage.Load(dataDir + "description.html", new HtmlLoadOptions());
MailMessage.Load(dataDir + "Message.mhtml", new MhtmlLoadOptions());
MailMessage.Load(dataDir + "Message.msg", new MsgLoadOptions());
// loading with custom options
EmlLoadOptions emlLoadOptions = new EmlLoadOptions
{
PrefferedTextEncoding = Encoding.UTF8,
PreserveTnefAttachments = true
};
MailMessage.Load(dataDir + "description.html", emlLoadOptions);
HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions
{
PrefferedTextEncoding = Encoding.UTF8,
ShouldAddPlainTextView = true,
PathToResources = dataDir
};
MailMessage.Load(dataDir + "description.html", emlLoadOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
// Create an instance of MailMessage class
MailMessage message = new MailMessage {From = "sender@sender.com"};
message.To.Add("receiver@gmail.com");
// Load an attachment
Attachment attachment = new Attachment(dataDir + "1.txt");
// Add Multiple Attachment in instance of MailMessage class and Save message to disk
message.Attachments.Add(attachment);
message.AddAttachment(new Attachment(dataDir + "1.jpg"));
message.AddAttachment(new Attachment(dataDir + "1.doc"));
message.AddAttachment(new Attachment(dataDir + "1.rar"));
message.AddAttachment(new Attachment(dataDir + "1.pdf"));
message.Save(dataDir + "outputAttachments_out.msg", SaveOptions.DefaultMsgUnicode);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mail = MailMessage.Load(dataDir + "tnefWithMsgInside.eml", new EmlLoadOptions() { PreserveEmbeddedMessageFormat = true });
FileFormatType fileFormat = FileFormatUtil.DetectFileFormat(mail.Attachments[0].ContentStream).FileFormatType;
Console.WriteLine("Embedded message file format: " + fileFormat);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mailMessage = MailMessage.Load(dataDir + "Attachments.eml");
// Save as eml with preserved original boundares
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
PreserveOriginalBoundaries = true
};
mailMessage.Save(dataDir + "PreserveOriginalBoundaries_out.eml", emlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mailMessage = MailMessage.Load(dataDir + "PreserveOriginalBoundaries.eml");
// Save as eml with preserved attachment
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments
};
mailMessage.Save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
var eml = MailMessage.Load(dataDir + "sample.eml", new EmlLoadOptions());
var options = MapiConversionOptions.UnicodeFormat;
//Preserve Embedded Message Format
options.PreserveEmbeddedMessageFormat = true;
//Convert EML to MSG with Options
var msg = MapiMessage.FromMailMessage(eml, options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
const string pageHeader = @"<div><div class='pageHeader'>&quot;Panditharatne, Mithra&quot; &lt;mithra.panditharatne@cibc.com&gt;<hr/></div>";
MailMessage message = MailMessage.Load(dataDir + "Message.eml");
MhtMessageFormatter mailFormatter = new MhtMessageFormatter();
MailMessage copyMessage = message.Clone();
mailFormatter.Format(copyMessage);
Console.WriteLine(copyMessage.HtmlBody.Contains(pageHeader) ? "True" : "False");
MhtFormatOptions options = MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.WriteCompleteEmailAddress;
mailFormatter.Format(message, options);
if (!message.HtmlBody.Contains(pageHeader))
Console.WriteLine("True");
else
Console.WriteLine("False");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MsgLoadOptions options = new MsgLoadOptions();
options.PreserveTnefAttachments = true;
MailMessage eml = MailMessage.Load(dataDir + "EmbeddedImage1.msg", options);
foreach (Attachment attachment in eml.Attachments)
{
Console.WriteLine(attachment.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
List<Appointment> appointments = new List<Appointment>();
CalendarReader reader = new CalendarReader(dataDir + "US-Holidays.ics");
while (reader.NextEvent())
{
appointments.Add(reader.Current);
}
//working with appointments...
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create the message
MailMessage msg = new MailMessage();
msg.From = "sender@sender.com";
msg.To = "receiver@receiver.com";
msg.Subject = "the subject of the message";
// Set delivery notifications for success and failed messages
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.OnFailure;
// Add the MIME headers
msg.Headers.Add_("Disposition-Notification-To", "sender@sender.com");
msg.Headers.Add_("Disposition-Notification-To", "sender@sender.com");
// Send the message
SmtpClient client = new SmtpClient("host", "username", "password");
client.Send(msg);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Create an instance of Attachment class
Attachment attachment;
// Load attachment to your Mail Message, Add attachment to your Mail Message and Remove attachment from your MailMessage
attachment = new Attachment(@"e:\1.txt");
message.Attachments.Add(attachment);
message.Attachments.Remove(attachment);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string dstEmailRemoved = dataDir + "RemoveAttachments.msg";
// Create an instance of MailMessage class
MailMessage message = new MailMessage();
message.From = "sender@sender.com";
message.To.Add("receiver@gmail.com");
// Load an attachment
Attachment attachment = new Attachment(dataDir + "1.txt");
// Add Multiple Attachment in instance of MailMessage class and Save message to disk
message.Attachments.Add(attachment);
message.AddAttachment(new Attachment(dataDir + "1.jpg"));
message.AddAttachment(new Attachment(dataDir + "1.doc"));
message.AddAttachment(new Attachment(dataDir + "1.rar"));
message.AddAttachment(new Attachment(dataDir + "1.pdf"));
// Remove attachment from your MailMessage and Save message to disk after removing a single attachment
message.Attachments.Remove(attachment);
message.Save(dstEmailRemoved, SaveOptions.DefaultMsgUnicode);
// Create a loop to display the no. of attachments present in email message
foreach (Attachment getAttachment in message.Attachments)
{
// Save your attachments here and Display the the attachment file name
getAttachment.Save(dataDir + "/RemoveAttachments/" + "attachment_out" + getAttachment.Name);
Console.WriteLine(getAttachment.Name);
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
//sample input file
string fileName = "EmlWithLinkedResources.eml";
//Load the test message with Linked Resources
MailMessage msg = MailMessage.Load(dataDir + fileName);
//Remove a LinkedResource
msg.LinkedResources.RemoveAt(0, true);
//Now clear the Alternate View for linked Resources
msg.AlternateViews[0].LinkedResources.Clear(true);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
//sample input file
string fileName = "EmlWithLinkedResources.eml";
//Load the test message with Linked Resources
MailMessage msg = MailMessage.Load(dataDir + fileName);
//Remove a LinkedResource
msg.LinkedResources.RemoveAt(0, true);
//Now clear the Alternate View for linked Resources
msg.AlternateViews[0].LinkedResources.Clear(true);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Load attachment to your Mail Message, Add attachment and Remove attachment from your MailMessage
Attachment attachment = new Attachment(@"e:\1.txt");
message.Attachments.Add(attachment);
message.Attachments.Remove(attachment);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
string fileName = "Meeting with Recurring Occurrences.msg";
MailMessage msg = MailMessage.Load(dataDir + fileName);
MhtSaveOptions options = new MhtSaveOptions();
{
options.MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.RenderCalendarEvent;
//Format the output details if required - optional
//Set the display for Start Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.Start))
options.FormatTemplates[MhtTemplateName.Start] = @"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.