Utility Features - MailMessage

Encrypting and Decrypting Messages

Aspose.Email provides the facility to encrypt and decrypt email messages using the X509Certificates. This article shows how an existing or new message can be loaded and encrypted using MailMessage. The Encrypt() and Decrypt() methods return a MailMessage object for the applied effects and need to be taken care of while encrypting/decrypting messages. Encrypting and decrypting messages involves the following steps:

  1. Create a new message or load an existing one
  2. Load an encryption certificate using the X509Certificate object
  3. Encrypt the message using the certificate
  4. Send the message or save it
  5. Decrypt the message as required

The following code snippet shows you how to encrypt and decrypt messages.

// 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");

Check a Message for Encryption

Aspose.Email MailMessage class allows you to check if a message is encrypted or not. The IsEncrypted property of MailMessage allows you to check this as shown in the following code sample.

// 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);

Email messages containing TNEF attachments

Transport Neutral Encapsulation Format (TNEF) is a proprietary email attachment format used by Microsoft Outlook and Microsoft Exchange Server. The Aspose.Email API allows you to read email messages that have TNEF attachments and modify the contents of the attachment. The email can then be saved as a normal email or to the same format, preserving TNEF attachments. This article shows different code samples for working with messages containing TNEF attachments. This article also shows how to create TNEF EML files from Outlook MSG files.

Read a Message Preserving TNEF Attachments

The following code snippet shows you how to read a message preserving TNEF attachments.

// 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);
}

Read a Message without Preserving TNEF Attachments

The following code snippet shows you how to read a message without preserving TNEF attachments.

Updating Resources in a TNEF Attachment and Preserving TNEF Format

The following code snippet shows you how to update resources in a TNEF attachment and preserve TNEF format.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
public static void TestUpdateResources(string dataDir)
{
string fileName = dataDir + "tnefEML1.eml";
string imgFileName = dataDir + "Untitled.jpg";
string outFileName = dataDir + "UpdateTNEFAttachments_out.eml";
MailMessage originalMailMessage = MailMessage.Load(fileName);
UpdateResources(originalMailMessage, imgFileName);
EmlSaveOptions emlSo = new EmlSaveOptions(MailMessageSaveType.EmlFormat);
emlSo.FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments;
originalMailMessage.Save(outFileName, emlSo);
}
private static void UpdateResources(MailMessage msg, string imgFileName)
{
for (int i = 0; i < msg.Attachments.Count; i++)
{
if ((msg.Attachments[i].ContentType.MediaType == "image/png") || (msg.Attachments[i].ContentType.MediaType == "application/octet-stream" && Path.GetExtension(msg.Attachments[i].ContentType.Name) == ".jpg"))
{
msg.Attachments[i].ContentStream = new MemoryStream(File.ReadAllBytes(imgFileName));
}
else if ((msg.Attachments[i].ContentType.MediaType == "message/rfc822") || (msg.Attachments[i].ContentType.MediaType == "application/octet-stream" && Path.GetExtension(msg.Attachments[i].ContentType.Name) == ".msg"))
{
MemoryStream ms = new MemoryStream();
msg.Attachments[i].Save(ms);
ms.Position = 0;
MailMessage embeddedMessage = MailMessage.Load(ms);
UpdateResources(embeddedMessage, imgFileName);
MemoryStream msProcessedEmbedded = new MemoryStream();
embeddedMessage.Save(msProcessedEmbedded, SaveOptions.DefaultMsgUnicode);
msProcessedEmbedded.Position = 0;
msg.Attachments[i].ContentStream = msProcessedEmbedded;
}
}
foreach (LinkedResource att in msg.LinkedResources)
{
if (att.ContentType.MediaType == "image/png")
att.ContentStream = new MemoryStream(File.ReadAllBytes(imgFileName));
}
}

Adding New Attachments to the Main Message Containing TNEF

The following code snippet shows you how to add new attachments to the main message containing TNEF.

// 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);

Creating TNEF EML from MSG

Outlook MSGs sometimes contain information such as tables and text styles that may get disturbed if these are converted to EML. Creating TNEF messages from such MSG files allows to retain the formatting and even send such messages via the email clients retaining the formatting. The MailConversionOptions.ConvertAsTnef property is used to achieve this. The following code snippet shows you how to create TNEF EML from MSG.

// 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 creating the TNEF, the following sample code can be used.

// 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);

Detect If a Message is TNEF

The following code snippet shows you how to detect if a message is TNEF.

// 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());

Processing Bounced Messages

It is very common that a message sent to a recipient may bounce for any reason such as an invalid recipient address. Aspose.Email API has the capability to process such a message for checking if it is a bounced email or a regular email message. The CheckBounced method of the MailMessage class returns a valid result if the email message is a bounced email. This article shows the usage of the BounceResult class that provides the capability of checking if a message is a bounced email. It further gives detailed information about the recipients, action taken and the reason for the notification. The following code snippet shows you how to process bounced messages.

// 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();

Bayesian Spam Analyzer

Aspose.Email provides email filtering using a Bayesian spam analyzer. It provides the SpamAnalyzer class for this purpose. This article shows how to train the filter to distinguish between spam and regular emails based on the words database.

// 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);
}