How to Load an Existing Email Message & Modify its Contents in Java Apps
This technical tip shows how to java developers can load and modify an existing email message inside their java application using Aspose.Email Java API. Aspose.Email API allows developer to load any existing email message and modify its contents before saving back to the disk. One notable point is to specify the MessageFormat while loading the email message from the disk. In addition, it is important to specify the correct MailMessageSaveType while saving the message back to disk.
//Adding Attachments to a New Email Message
public static void main(String[] args)
{
// Base folder for reading and writing files
String strBaseFolder = "D:\\Data\\Aspose\\resources\\";
//Initialize and Load an existing MSG file by specifying the MessageFormat
MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());
//Initialize a String variable to get the Email Subject
String subject = email.getSubject();
//Append some more information to Subject
subject = subject + " This text is added to the existing subject";
//Set the Email Subject
email.setSubject(subject);
//Initialize a String variable to get the Email's HTML Body
String body = email.getHtmlBody();
//Apppend some more information to the Body variable
body = body + "<br> This text is added to the existing body";
//Set the Email Body
email.setHtmlBody(body);
//Initialize MailAddressCollection object
MailAddressCollection contacts = new MailAddressCollection();
//Retrieve Email's TO list
contacts = email.getTo();
//Check if TO list has some values
if (contacts.size() > 0)
{
//Remove the first email address
contacts.remove(0);
//Add another email address to collection
contacts.add("to1@domain.com");
}
//Set the collection as Email's TO list
email.setTo(contacts);
//Initialize MailAddressCollection
contacts = new MailAddressCollection();
//Retrieve Email's CC list
contacts = email.getCC();
//Add another email address to collection
contacts.add("cc2@domain.com");
//Set the collection as Email's CC list
email.setCC(contacts);
//Save the Email message to disk by specifying the MessageFormat
email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
}
//Loading a Message with Load Options
//To load a message with specific load options, Aspose.Email provides the MessageLoadOptions class that can be used as follow:
MesageLoadOptions options = new MesageLoadOptions();
options.PrefferedTextEncoding = Encoding.getEncoding(1252);
options.setMessageFormat(MessageFormat.getMsg());
MailMessage eml = MailMessage.Load("EMAIL_497563\\test3.msg", options);
//your code here...
Url: http://www.aspose.com/java/email-component.aspx
Language: Java | User: Sheraz Khan | Created: Sep 10, 2014 | Tags: Load existing email message in Java modify content of email message Modifying an existing Email Message java Email library specify Message Format save message back to disk Aspose.Email API