Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gists of Aspose.Email for Java
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Gists of Aspose.Email for Java
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String location = "Room 5";
java.util.Calendar c = java.util.Calendar.getInstance();
c.set(2011, 11, 10, 10, 12, 11);
Date startDate = c.getTime();
c.set(2012, 10, 13, 13, 11, 12);
Date endDate = c.getTime();
MailAddress organizer = new MailAddress("aaa@amail.com", "Organizer");
MailAddressCollection attendees = new MailAddressCollection();
MailAddress attendee1 = new MailAddress("bbb@bmail.com", "First attendee");
MailAddress attendee2 = new MailAddress("ccc@cmail.com", "Second attendee");
attendee1.setParticipationStatus(ParticipationStatus.Accepted);
attendee2.setParticipationStatus(ParticipationStatus.Declined);
attendees.addMailAddress(attendee1);
attendees.addMailAddress(attendee2);
Appointment target = new Appointment(location, startDate, endDate, organizer, attendees);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IcsSaveOptions saveOptions = new IcsSaveOptions();
saveOptions.setAction(AppointmentAction.Create);
CalendarWriter writer = new CalendarWriter("WirteMultipleEventsToICS_out.ics", saveOptions);
//Set the start and end date of meeting
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2018, Calendar.JUNE, 19, 19, 0, 0); //19 Jan, 2015 - 1900
Date startDate = calendar.getTime();
calendar.set(2018, Calendar.JUNE, 19, 20, 0, 0);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addItem(new MailAddress("recepientEmail@gmail.com"));
try {
for (int i = 0; i < 10; i++) {
//create Appointment instance
Appointment app = new Appointment("Room 112", //location
startDate, //start time
endDate, //end time
new MailAddress("organizer@domain.com"), //organizer
attendees //attendee
);
app.setDescription("Test body " + i);
app.setSummary("Test summary:" + i);
writer.write(app);
}
} finally {
writer.dispose();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(AddAndRetrieveAttachmentFromCalendarItems.class) + "email/";
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2016, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2016, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee_address@domain.com", "Attendee"));
WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);
Appointment app = new Appointment("Appointment Location", "Appointment Summary", "Appointment Description", startDate, endDate, new MailAddress("organizer_address@domain.com", "Organizer"),
attendees, expected);
//Attach a file from disc to this appointment
File file = new File(dataDir + "sample.xlsx");
FileInputStream fis = new FileInputStream(file);
Attachment att = new Attachment(fis, file.getName());
app.getAttachments().addItem(att);
fis.close();
String savedFile = "appWithAttachments.ics";
app.save(dataDir + savedFile, AppointmentSaveFormat.Ics);
Appointment app2 = Appointment.load(dataDir + savedFile);
System.out.println("Total Attachments: " + app2.getAttachments().size());
for (int i = 0; i < app2.getAttachments().size(); i++) {
att = app2.getAttachments().get_Item(i);
System.out.println(att.getName());
//Save the attachment to disc
att.save(dataDir + att.getName());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(AddAttachmentToANewEmailMessage.class) + "email/";
//Create an instance of MailMessage class
MailMessage message = new MailMessage();
//From
message.setFrom(new MailAddress("sender@sender.com"));
//To
message.getTo().addMailAddress(new MailAddress("receiver@gmail.com"));
//Adding 1st attachment
//Create an instance of Attachment class
Attachment attachment;
//Load an attachment
attachment = new Attachment(dataDir + "1.txt");
//Add attachment in instance of MailMessage class
message.getAttachments().addItem(attachment);
//Add 2nd Attachment
message.getAttachments().addItem(new Attachment(dataDir + "1.jpg"));
//Add 3rd Attachment
message.getAttachments().addItem(new Attachment(dataDir + "1.doc"));
//Add 4th Attachment
message.getAttachments().addItem(new Attachment(dataDir + "1.rar"));
//Add 5th Attachment
message.getAttachments().addItem(new Attachment(dataDir + "1.pdf"));
//Save message to disc
message.save(dataDir + "AddAttachmentToANewEmailMessage_out.msg", SaveOptions.getDefaultMsg());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(AddEmbeddedImagesToEmailMessage.class) + "email/";
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set sender information
message.setFrom(new MailAddress("from@domain.com", "Sender Name", false));
// Add recipients
message.getTo().addItem(new MailAddress("to1@domain.com", "Recipient 1", false));
message.getTo().addItem(new MailAddress("to2@domain.com", "Recipient 2", false));
// Set subject of the message
message.setSubject("New message created by Aspose.Email for Java");
// Set Html body. It also contains <img> tag with cid. cid = LinkedResource.ContentID
message.setHtmlBody("<b>This line is in bold.</b> <br/> <br/>" + "<font color=blue>This line is in blue color</font><br><br>" + "Here is an embedded image.<img src=cid:companylogo>");
// Add linked resource
LinkedResource res = new LinkedResource(dataDir + "barcode.png", MediaTypeNames.Image.PNG);
res.setContentId("companylogo");
// Add Linked resource to the message’s Linked resource colledction
message.getLinkedResources().addItem(res);
// Save message in EML, MSG and MHTML formats
message.save(dataDir + "EmbeddedImageToEmail_out.eml");
message.save(dataDir + "EmbeddedImageToEmail_out.msg");
message.save(dataDir + "EmbeddedImageToEmail_out.mhtml");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(AddOrRemoveAttachmentFromAnExistingMessage.class) + "email/";
//Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage message = MailMessage.load(dataDir + "EmailWithAttachment.eml");
//Initialize AttachmentCollection object with MailMessage Attachments
AttachmentCollection attachments = message.getAttachments();
System.out.println("Attachment Count: " + attachments.size());
//Check if AttachmentCollection size is greater than 0
if (attachments.size() > 0) {
//Remove Attachment from index location 0
attachments.removeAt(0);
System.out.println("Attachment Count: " + attachments.size());
}
//Add a PDF file as attachment to the message
message.addAttachment(new Attachment(dataDir + "1.pdf"));
System.out.println("Attachment Count: " + attachments.size());
//Save the Email message to disk
message.save(dataDir + "AddRemoveAttachmentFromAnExistingMessage_out.eml", SaveOptions.getDefaultEml());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void main(String[] args) {
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(BayesianSpamAnalyzer.class) + "email/";
SpamFilterTest(dataDir);
}
public static void SpamFilterTest(String dataDir) {
String hamFolder = dataDir + "ham";
String spamFolder = dataDir + "spam";
String testFolder = dataDir + "test";
String dataBaseFile = dataDir + "SpamFilterDatabase.txt";
teachAndCreateDatabase(hamFolder, spamFolder, dataBaseFile);
java.io.File folder = new java.io.File(testFolder);
java.io.File[] testFiles = folder.listFiles();
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile);
for (int i = 0; i < testFiles.length; i++) {
MailMessage msg = MailMessage.load(testFiles[i].getAbsolutePath());
System.out.println(msg.getSubject());
double probability = analyzer.test(msg);
printResult(probability);
}
}
private static void teachAndCreateDatabase(String hamFolder, String spamFolder, String dataBaseFile) {
java.io.File folder = new java.io.File(hamFolder);
java.io.File[] hamFiles = folder.listFiles();
folder = new java.io.File(spamFolder);
java.io.File[] spamFiles = folder.listFiles();
SpamAnalyzer analyzer = new SpamAnalyzer();
for (int i = 0; i < hamFiles.length; i++) {
MailMessage hamMailMessage;
try {
hamMailMessage = MailMessage.load(hamFiles[i].getAbsolutePath());
} catch (Exception e) {
continue;
}
System.out.println(i);
analyzer.trainFilter(hamMailMessage, false);
}
for (int i = 0; i < spamFiles.length; i++) {
MailMessage spamMailMessage;
try {
spamMailMessage = MailMessage.load(spamFiles[i].getAbsolutePath());
} catch (Exception e) {
continue;
}
System.out.println(i);
analyzer.trainFilter(spamMailMessage, true);
}
analyzer.saveDatabase(dataBaseFile);
}
private static void printResult(double probability) {
if (probability < 0.05)
System.out.println("This is ham)");
else if (probability > 0.95)
System.out.println("This is spam)");
else
System.out.println("Maybe spam)");
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
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.getTo().addMailAddress(new MailAddress("kyle@to.com", "Kyle Huang"));
// Specify Cc and Bcc email address along with a friendly name
message.getCC().addMailAddress(new MailAddress("guangzhou@cc.com", "Guangzhou Team"));
message.getBcc().addMailAddress(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.setHost("smtp.server.com");
client.setUsername("Username");
client.setPassword("Password");
client.setPort(25);
try
{
// Client.Send will send this message
client.send(message);
System.out.println("Message sent");
}
catch (Exception ex)
{
ex.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a message
MailMessage originalMsg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
if (originalMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
// Encrypt the message
MailMessage mailMsg = null;
try {
mailMsg = originalMsg.encrypt(Files.readAllBytes(publicCertFilePath), "");
if (mailMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// Decrypt the message
try {
mailMsg = mailMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
if (mailMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as Mht with header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
int iSaveOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader;
mhtSaveOptions.setMhtFormatOptions(iSaveOptions);
eml.save(dataDir + "ConvertingToMHTMLWithOptionalSettings_out.mht", mhtSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setSkipInlineImages(true);
eml.save(dataDir + "EmlToMhtmlWithoutInlineImages_out.mht", mhtSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as eml with preserved original boundares
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setPreserveOriginalBoundaries(true);
eml.save(dataDir + "PreserveOriginalBoundaries_out.eml", emlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage msg = MailMessage.load(dataDir + "test.eml", new EmlLoadOptions());
// Save the Email message to disk by using the SaveOptions
msg.save(dataDir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.getDefaultEml());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.load(dataDir + "test.eml");
//Save the Email message to disk in Unicode format
eml.save(dataDir + "LoadingEMLSavingToMSG_out.msg", SaveOptions.getDefaultMsgUnicode());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage mailMsg = new MailMessage();
mailMsg.setSubject("This is subject");
mailMsg.setBody("This is body");
String address = "a\"xasadf@xam.com";
mailMsg.setFrom(new MailAddress(address));
mailMsg.getTo().addMailAddress(new MailAddress(address));
MapiConversionOptions cOpt = MapiConversionOptions.getUnicodeFormat();
cOpt.setPreserveOriginalAddresses(true);
MapiMessage outlookMsg = MapiMessage.fromMailMessage(mailMsg, cOpt);
outlookMsg.save(dataDir + "PreservingOriginalEmailAddress_out.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Appointment appointment = Appointment.load(dataDir + "test.ics");
MailMessage outlookMsg = new MailMessage();
outlookMsg.addAlternateView(appointment.requestApointment());
MhtSaveOptions opt = SaveOptions.getDefaultMhtml();
opt.setMhtFormatOptions(opt.getMhtFormatOptions() | MhtFormatOptions.RenderCalendarEvent);
outlookMsg.save(dataDir + "RenderingCalendarEventsToMHTML_out.mht", opt);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "PreserveOriginalBoundaries.eml");
// Save as eml with preserved thef attachment
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);
eml.save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String fileName = dataDir + "EmailWithAttandEmbedded.eml";
MailMessage eml = MailMessage.load(fileName);
//final String outDir = "out path";
String outFileName = "EmailWithAttandEmbedded_out.html";
HtmlSaveOptions options = new HtmlSaveOptions();
options.setEmbedResources(false);
options.setSaveResourceHandler(new SaveResourceHandler() {
@Override
public void invoke(AttachmentBase attachment, String[] resourcePath) {
String dataDir = Utils.getSharedDataDir(ConvertEmailMessages.class) + "email/";
attachment.save(dataDir + attachment.getContentId());
resourcePath[0] = dataDir + attachment.getContentId();
}
});
eml.save(dataDir + outFileName, options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load(dataDir + "test.eml");
// Save as msg with preserved dates
MsgSaveOptions msgSaveOptions = new MsgSaveOptions(MailMessageSaveType.getOutlookMessageFormatUnicode());
msgSaveOptions.setPreserveOriginalDates(true);
eml.save(dataDir + "SavingAsMSGWithPreservedDates_out.msg", msgSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.load(dataDir + "test.eml");
eml.save(dataDir + "SavingMailMessageAsMHTML_out.mthml", SaveOptions.getDefaultMhtml());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage msg = MailMessage.load(dataDir + "Message.msg");
msg.save(dataDir + "SavingMessageAsHTML_out1.html", SaveOptions.getDefaultHtml());
//or
MailMessage eml = MailMessage.load(dataDir + "test.eml");
HtmlSaveOptions options = SaveOptions.getDefaultHtml();
options.setEmbedResources(false);
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress);
eml.save(dataDir + "SavingMessageAsHTML_out2.html", options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MapiMessage msg = MapiMessage.fromFile(dataDir + "Message.msg");
for (MapiRecipient rec : msg.getRecipients()) {
rec.getRecipientTrackStatus();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(CreateNewEmail.class) + "email/";
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set subject of the message
message.setSubject("New message created by Aspose.Email for Java");
// Set Html body
message.setHtmlBody("<b>This line is in bold.</b> <br/> <br/>" + "<font color=blue>This line is in blue color</font>");
// Set sender information
message.setFrom(new MailAddress("from@domain.com", "Sender Name", false));
// Add TO recipients
message.getTo().addMailAddress(new MailAddress("to1@domain.com", "Recipient 1", false));
message.getTo().addMailAddress(new MailAddress("to2@domain.com", "Recipient 2", false));
//Add CC recipients
message.getCC().addMailAddress(new MailAddress("cc1@domain.com", "Recipient 3", false));
message.getCC().addMailAddress(new MailAddress("cc2@domain.com", "Recipient 4", false));
// Save message in EML, MSG and MHTML formats
message.save(dataDir + "Message_out.eml", SaveOptions.getDefaultEml());
message.save(dataDir + "Message_out.msg", SaveOptions.getDefaultMsg());
message.save(dataDir + "Message_out.mhtml", SaveOptions.getDefaultMhtml());
//Save as OFT
try {
MsgSaveOptions options = SaveOptions.getDefaultMsgUnicode();
options.setSaveAsTemplate(true);
message.save(dataDir + "emlToOft_out.oft", options);
} finally {
if (message != null)
((IDisposable) message).dispose();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateNewEmail.class);
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set subject of the message
message.setSubject("New message created by Aspose.Email for Java");
// Set Html body
message.setHtmlBody("<b>This line is in bold.</b> <br/> <br/>" +
"<font color=blue>This line is in blue color</font>");
// Set sender information
message.setFrom(new MailAddress("from@domain.com", "Sender Name", false));
// Add TO recipients
message.getTo().addMailAddress(new MailAddress("to1@domain.com", "Recipient 1", false));
message.getTo().addMailAddress(new MailAddress("to2@domain.com", "Recipient 2", false));
//Add CC recipients
message.getCC().addMailAddress(new MailAddress("cc1@domain.com", "Recipient 3", false));
message.getCC().addMailAddress(new MailAddress("cc2@domain.com", "Recipient 4", false));
// Save message in EML, MSG and MHTML formats
message.save(dataDir + "Message.eml", SaveOptions.getDefaultEml());
message.save(dataDir + "Message.msg", SaveOptions.getDefaultMsg());
message.save(dataDir + "Message.mhtml", SaveOptions.getDefaultMhtml());
//Save as OFT
try
{
MsgSaveOptions options = SaveOptions.getDefaultMsgUnicode();
options.setSaveAsTemplate(true);
message.save("emlToOft.oft", options);
}
finally { if (eml != null)
((IDisposable)eml).dispose();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(DetectingFileFormat.class) + "email/";
//Detect file format
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "Message.msg");
//Gets the detected load format
System.out.println("The message format is: " + info.getFileFormatType());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(DetermineIfAttachmentIsEmbeddedMessage.class) + "email/";
MailMessage eml = MailMessage.load(dataDir + "EmailWithAttandEmbedded.eml");
if (eml.getAttachments().get_Item(0).isEmbeddedMessage()) {
System.out.println("Attachment is an embedded message");
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a loop to display the no. of attachments present in email message
for (Attachment attachment : message.getAttachments())
{
// Save your attachments here and Display the the attachment file name
attachment.save(dataDir + attachment.getName());
System.out.println(attachment.getName());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
//Create MailMessage instance by loading an Eml file
MailMessage message = MailMessage.load(dataDir + "test.eml");
System.out.print("From: ");
//Gets the sender info
System.out.println(message.getFrom());
System.out.print("To: ");
//Gets the recipients info
System.out.println(message.getTo());
System.out.print("Subject: ");
//Gets the subject
System.out.println(message.getSubject());
System.out.print("HtmlBody: ");
//Gets the htmlbody
System.out.println(message.getHtmlBody());
System.out.print("TextBody: ");
//Gets the textbody
System.out.println(message.getBody());
System.out.print("HtmlBodyText: ");
//Gets the textbody from HTML
System.out.println(message.getHtmlBodyText());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
//Create MailMessage instance by loading an Eml file
MailMessage message = MailMessage.load(dataDir + "test.eml");
System.out.print("From: ");
//Gets the sender info
System.out.println(message.getFrom());
System.out.print("To: ");
//Gets the recipients info
System.out.println(message.getTo());
System.out.print("Subject: ");
//Gets the subject
System.out.println(message.getSubject());
System.out.print("HtmlBody: ");
//Gets the htmlbody
System.out.println(message.getHtmlBody());
System.out.print("TextBody: ");
//Gets the textbody
System.out.println(message.getTextBody());
System.out.print("HtmlBodyText: ");
//Gets the textbody from HTML
System.out.println(message.getHtmlBodyText());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String sender = "test@gmail.com";
String recipient = "test@email.com";
MailMessage message = new MailMessage(sender, recipient, "", "");
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(2016, Calendar.NOVEMBER, 1, 0, 0, 0);
Date startDate = calendar.getTime();
calendar.set(2016, Calendar.DECEMBER, 1);
Date endDate = calendar.getTime();
MailAddressCollection attendees = new MailAddressCollection();
attendees.addMailAddress(new MailAddress("attendee_address@aspose.com", "Attendee"));
//WeeklyRecurrencePattern expected = new WeeklyRecurrencePattern(3);
Appointment app = new Appointment("", startDate, endDate, new MailAddress("organizer_address@aspose.com", "Organizer"), attendees);
/*
* Appointment app = new Appointment("Appointment Location",
* "Appointment Summary", "Appointment Description", startDate, endDate,
* new MailAddress("organizer_address@aspose.com", "Organizer"),
* attendees, expected);
*/
//Set the Appointment as Draft
app.setMethod(AppointmentMethodType.Publish);
message.addAlternateView(app.requestApointment());
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as draft.
msg.save(dataDir + "appointment-draft.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String ical = "BEGIN:VCALENDAR\r\nMETHOD:PUBLISH\r\nPRODID:-//Aspose Ltd//iCalender Builder (v3.0)//EN\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nATTENDEE;CN=test@gmail.com:mailto:test@gmail.com\r\nDTSTART:20130220T171439\r\nDTEND:20130220T174439\r\nDTSTAMP:20130220T161439Z\r\nEND:VEVENT\r\nEND:VCALENDAR";
String sender = "test@gmail.com";
String recipient = "test@email.com";
MailMessage message = new MailMessage(sender, recipient, "", "");
AlternateView av = AlternateView.createAlternateViewFromString(ical, new ContentType("text/calendar"));
message.getAlternateViews().addItem(av);
MapiMessage msg = MapiMessage.fromMailMessage(message);
// Save the appointment as draft.
msg.save(dataDir + "DraftAppointment.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
//Create MailMessage instance by loading an EML file
MailMessage message = MailMessage.load(dataDir + "test.eml");
System.out.println("Printing all Headers:\n\n");
//Print out all the headers
for (int i=0; i< message.getHeaders().size(); i++)
System.out.println(message.getHeaders().get(i));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage mail = MailMessage.load(dataDir + "test.eml");
String decodedValue = mail.getHeaders().getDecodedValue("Thread-Topic");
System.out.println(decodedValue);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Insert Header at Specific Location
MailMessage eml = MailMessage.load(dataDir + "test.eml");
eml.getHeaders().insert("Received", "Value");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set subject of the message
message.setSubject("New message created by Aspose.Email for Java");
// Set Html body
message.setHtmlBody("<b>This line is in bold.</b> <br/> <br/>" +
"<font color=blue>This line is in blue color</font>");
// Set sender information
message.setFrom(new MailAddress("from@domain.com", "Sender Name", false));
// Add TO recipients
message.getTo().addItem(new MailAddress("to@domain.com", "Recipient 1", false));
// Message subject
message.setSubject("Customizing Email Headers");
// Specify Date
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date date = calendar.getTime();
message.setDate(date);
// Specify XMailer
message.setXMailer("Aspose.Email");
// Specify Secret Header
message.getHeaders().add("secret-header", "mystery");
// Save message to disc
message.save(dataDir + "SetEmailHeaders_out.msg", SaveOptions.getDefaultMsg());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String publicCertFileName = dataDir + "MyKey.cer";
String privateCertFileName = dataDir + "MyPFX.pfx";
Path publicCertFilePath = Paths.get(publicCertFileName);
Path privateCertFilePath = Paths.get(privateCertFileName);
// Create a message
MailMessage msg = new MailMessage("atneostthaecrcount@gmail.com", "atneostthaecrcount@gmail.com", "Test subject", "Test Body");
// Encrypt the message
MailMessage eMsg = null;
try {
eMsg = msg.encrypt(Files.readAllBytes(publicCertFilePath), "");
if (eMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// Decrypt the message
MailMessage dMsg = null;
try {
dMsg = eMsg.decrypt(Files.readAllBytes(privateCertFilePath), "password");
if (dMsg.isEncrypted() == true)
System.out.println("Its encrypted");
else
System.out.println("Its NOT encrypted");
} catch (IOException e) {
e.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
eml.save(dataDir + "testEml_out.eml", SaveOptions.getDefaultEml());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage msg = MailMessage.load(filename, new MsgLoadOptions());
msg.setDate(new Date());
// Set the timezone offset in seconds
msg.setTimeZoneOffset(5*60*60*1000);
MhtSaveOptions mhtOptions = new MhtSaveOptions();
mhtOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader);
msg.save(dataDir + "ExportToMHTWithCustomTimezone_out.mhtml", mhtOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(ExtractAttachments.class) + "email/";
//Initialize and Load an existing EML file
MailMessage msg = MailMessage.load(dataDir + "EmailWithAttachment.eml", new EmlLoadOptions());
//Initialize AttachmentCollection object with MailMessage Attachments
AttachmentCollection attachments = msg.getAttachments();
//Iterate over the AttachmentCollection
for (int index = 0; index < attachments.size(); index++) {
//Initialize Attachment object and Get the indexed Attachment reference
Attachment attachment = (Attachment) attachments.get_Item(index);
//Display Attachment Name
System.out.println(attachment.getName());
//Save Attachment to disk
attachment.save(dataDir + "attachment_" + attachment.getName());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
static void ExtractInlineAttachments(String dataDir)
{
MapiMessage message = MapiMessage.fromFile(dataDir + "MSG file with RTF Formatting.msg");
MapiAttachmentCollection attachments = message.getAttachments();
for (Object untypedAttachment : attachments)
{
MapiAttachment attachment = (MapiAttachment) untypedAttachment;
if(IsAttachmentInline(attachment))
{
try
{
SaveAttachment(attachment, UUID.randomUUID().toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
static boolean IsAttachmentInline(MapiAttachment attachment)
{
MapiObjectProperty objectData = attachment.getObjectData();
if (objectData == null)
return false;
for (Object prop : attachment.getObjectData().getProperties().getValues())
{
MapiProperty property = (MapiProperty)prop;
if ("\u0003ObjInfo".equals(property.getName()))
{
byte[] data = property.getData();
int odtPersist1 = data[1] << 8 | data[0];
return (odtPersist1 & 0x40) == 0;
}
}
return false;
}
static void SaveAttachment(MapiAttachment attachment, String fileName) throws IOException, FileNotFoundException
{
for (Object prop : attachment.getObjectData().getProperties().getValues())
{
MapiProperty property = (MapiProperty)prop;
if ("Package".equals(property.getName()))
{
FileOutputStream fs;
try
{
fs = new FileOutputStream(fileName);
fs.write(property.getData(), 0, property.getData().length);
}
catch (java.io.IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Appointment appointment = Appointment.load(dataDir + "test.ics");
AppointmentFormattingOptions formattingOptions = AppointmentFormattingOptions.createAsHtml();
formattingOptions.setLocationFormat("<FONT SIZE=2 FACE=\"Arial\"><b>Where: {0}</b></FONT><BR>");
formattingOptions.setTitleFormat("<FONT SIZE=2 FACE=\"Arial\"><b>Subject: {0}</b></FONT><BR>");
formattingOptions.setDescriptionFormat("<P><FONT SIZE=2 FACE=\"Arial\">-----------<br><i>{0}</i></FONT></P>");
System.out.println(appointment.getAppointmentText(formattingOptions));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Appointment appointment = Appointment.load(dataDir + "test.ics");
AppointmentFormattingOptions formattingOptions = new AppointmentFormattingOptions();
formattingOptions.setLocationFormat("Where: {0}");
formattingOptions.setTitleFormat("Subject: {0}");
formattingOptions.setDescriptionFormat("\r\n*~*~*~*~*~*~*~*~*~*\r\n{0}");
System.out.println(appointment.getAppointmentText(formattingOptions));
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Loading with default options
// Load from eml
MailMessage eml = MailMessage.load("test.eml", new EmlLoadOptions());
// Load from html
MailMessage html = MailMessage.load("test.html", new HtmlLoadOptions());
// load from mhtml
MailMessage mhtml = MailMessage.load("test.mhtml", new MhtmlLoadOptions());
// load from msg
MailMessage msg = MailMessage.load("test.msg", new MsgLoadOptions());
// load from thef fomat
MailMessage thef = MailMessage.load("winmail.dat", new TnefLoadOptions());
// Loading with custom options
EmlLoadOptions opt = new EmlLoadOptions();
opt.setPreserveTnefAttachments(true);
MailMessage emlMailMessage = MailMessage.load("test.html", opt);
HtmlLoadOptions htmlOpt = new HtmlLoadOptions();
htmlOpt.shouldAddPlainTextView(true);
MailMessage htmlMailMessage = MailMessage.load("test.html", htmlOpt);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(ModifyAnExistingEmailMessage.class) + "email/";
//Initialize and Load an existing MSG file by specifying the MessageFormat
MailMessage email = MailMessage.load(dataDir + "Message.msg");
//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.removeAt(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
email.save(dataDir + "ModifingAnExistingEmailMessage_out.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void main(String[] args) {
//create a new MailMessage instance as a template
MailMessage template = new MailMessage();
//add template field to subject
template.setSubject("Hello, #FirstName#");
template.setFrom(MailAddress.to_MailAddress("sale@aspose.com"));
//add template field to receipt
template.getTo().addMailAddress(new MailAddress("#Receipt#", true));
//add template field to html body
//use GetSignment as the template routine, which will provide the same signment.
template.setHtmlBody("Dear #FirstName# #LastName#, &lt;br&gt;&lt;br&gt;Thank you for your interest in &lt;STRONG&gt;Aspose.Network&lt;/STRONG&gt;.&lt;br&gt;&lt;br&gt;Have fun with it.&lt;br&gt;&lt;br&gt;#GetSignature()#");
//create a new TemplateEngine with the template message.
TemplateEngine engine = new TemplateEngine(template);
//register the GetSignment as a template routine, for we use it in the template.
engine.registerRoutine("GetSignature", new TemplateRoutine() {
public Object invoke(Object[] args) {
return getSignature(args);
}
});
//fill a DataTable as data source
DataTable dt = new DataTable();
dt.getColumns().add("Receipt");
dt.getColumns().add("FirstName");
dt.getColumns().add("LastName");
DataRow dr;
dr = dt.newRow();
dr.set("Receipt", "Nancy.Davolio&lt;Nancy@somedomain.com&gt;");
dr.set("FirstName", "Nancy");
dr.set("LastName", "Davolio");
dt.getRows().add(dr);
dr = dt.newRow();
dr.set("Receipt", "Andrew.Fuller&lt;Andrew@somedomain.com&gt;");
dr.set("FirstName", "Andrew");
dr.set("LastName", "Fuller");
dt.getRows().add(dr);
dr = dt.newRow();
dr.set("Receipt", "Janet.Leverling&lt;Janet@somedomain.com&gt;");
dr.set("FirstName", "Janet");
dr.set("LastName", "Leverling");
dt.getRows().add(dr);
MailMessageCollection messages;
try
{
//create the messages from the template and datasource.
messages = engine.instantiate(dt);
}
catch (MailException ex)
{
System.out.println(ex.toString());
}
}
public static Object getSignature(Object[] args) {
return "John Smith&lt;br&gt;Product Lead&lt;br&gt;Aspose Ltd.&lt;br&gt;".concat(DateTime.getNow().toShortDateString());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
EmlLoadOptions options = new EmlLoadOptions();
options.setPreserveEmbeddedMessageFormat(true);
MailMessage mail = MailMessage.load(dataDir + "tnefWithMsgInside.eml", options);
int fileFormat = FileFormatUtil.detectFileFormat(mail.getAttachments().get_Item(0).getContentStream()).getFileFormatType();
System.out.println("Embedded message file format: " + fileFormat);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = MailMessage.load("path", new EmlLoadOptions());
MapiConversionOptions options = MapiConversionOptions.getUnicodeFormat();
options.setPreserveEmbeddedMessageFormat(true);
MapiMessage msg = MapiMessage.fromMailMessage(eml, options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(ProcessBouncedMessages.class) + "email/";
String fileName = "failed.msg";
MailMessage mail = MailMessage.load(dataDir + fileName);
BounceResult result = mail.checkBounced();
System.out.println(fileName);
System.out.println("IsBounced : " + result.isBounced());
System.out.println("Action : " + result.getAction());
System.out.println("Recipient : " + result.getRecipient());
System.out.println();
fileName = "failed1.msg";
mail = MailMessage.load(dataDir + fileName);
result = mail.checkBounced();
System.out.println(fileName);
System.out.println("IsBounced : " + result.isBounced());
System.out.println("Action : " + result.getAction());
System.out.println("Recipient : " + result.getRecipient());
System.out.println("Reason : " + result.getReason());
System.out.println("Status : " + result.getStatus());
System.out.println("OriginalMessage ToAddress 1: " + result.getOriginalMessage().getTo().get_Item(0).getAddress());
System.out.println();
fileName = "test.eml";
mail = MailMessage.load(dataDir + fileName);
result = mail.checkBounced();
System.out.println(fileName);
System.out.println("IsBounced : " + result.isBounced());
System.out.println("Action : " + result.getAction());
System.out.println("Recipient : " + result.getRecipient());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void main(String[] args) {
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(ReadEmbeddedEmailAttachmentsFromMessage.class) + "email/";
try {
MailMessage message = MailMessage.load(dataDir + "EmailWithAttandEmbedded.eml");
parseMessage(message, dataDir);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void parseMessage(MailMessage message, String dataDir) {
System.out.println("Subject: " + message.getSubject());
System.out.println("Extracting attachments....");
for (int i = 0; i < message.getAttachments().size(); i++) {
Attachment att = (Attachment) message.getAttachments().get_Item(i);
System.out.println("Attachment Name: " + att.getName());
// Get the name of attachment. If msg subject contains characters like :, /, \ etc., replace with space
// because windows cannot save files with these characters also save first 50 characters as file name to avoid long file names
String attFileName = att.getName().replace(".eml", "").replace(":", " ").replace("\\", " ").replace("/", " ").replace("?", "");
if (attFileName.length() > 50) {
attFileName = attFileName.substring(0, 50);
}
String attExt = (att.getName().substring(att.getName().lastIndexOf("."), att.getName().lastIndexOf(".") + 4));
// Save the attachment to disk
att.save(dataDir + attFileName + attExt);
// Check if it is an orphaned text attachment file (ATT00001.txt....) and of type eml
if ((attExt.equals(".eml")) || (att.getContentType().getMediaType().equals("text/plain") && att.getName().contains(".txt") == true && att.getName().contains("ATT") == true)) {
// Try to load this text file in MailMessage
MailMessage attMsg = MailMessage.load(dataDir + attFileName + attExt);
// Call the function recursively to parse this message and attachments
ParseMessage(attMsg, dataDir);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
EmlLoadOptions options = new EmlLoadOptions();
// This will Preserve the TNEF attachment as it is, file contains the TNEF attachment
options.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "tnefEml.eml", options);
for (Attachment attachment : eml.getAttachments())
{
System.out.println(attachment.getName());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(DisplayEmailInformation.class) + "email/";
List<Appointment> appointments = new ArrayList<Appointment>();
CalendarReader reader = new CalendarReader(dataDir + "US-Holidays.ics");
while (reader.nextEvent())
{
appointments.add(reader.getCurrent());
}
System.out.println("Number of events read: " + appointments.size());
//Process appointments loaded from events
//Reading events from a specific index
appointments = new ArrayList<Appointment>();
AppointmentLoadOptions options = new AppointmentLoadOptions();
options.setEventIndex(4);
reader = new CalendarReader(dataDir + "US-Holidays.ics", options);
//start reading from 4th appointment...
while (reader.nextEvent())
{
appointments.add(reader.getCurrent());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String fileName = "test.eml";
MailMessage msg = MailMessage.load(fileName);
msg.getLinkedResources().removeAt(0, true);
msg.getAlternateViews().get_Item(0).getLinkedResources().clear(true);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = Utils.getSharedDataDir(RenderingCalendarEvents.class) + "email/";
MailMessage msg = MailMessage.load(dataDir + "Meeting with Recurring Occurrences.msg");
MhtSaveOptions options = new MhtSaveOptions();
{
options.setMhtFormatOptions(MhtFormatOptions.WriteHeader | MhtFormatOptions.RenderCalendarEvent);
//Format the output details if required - optional
//Set the display for Start Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.START))
options.getFormatTemplates().set_Item(MhtTemplateName.START,"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.START, "<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for End Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.END))
options.getFormatTemplates().set_Item(MhtTemplateName.END, "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.END, "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Recurrence Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.RECURRENCE))
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE,"<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.RECURRENCE, "<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RecurrencePattern Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.RECURRENCE_PATTERN))
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE_PATTERN, "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.RECURRENCE_PATTERN, "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Organizer Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.ORGANIZER))
options.getFormatTemplates().set_Item(MhtTemplateName.ORGANIZER, "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.ORGANIZER, "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RequiredAttendees Property
if (options.getFormatTemplates().containsKey(MhtTemplateName.REQUIRED_ATTENDEES))
options.getFormatTemplates().set_Item(MhtTemplateName.REQUIRED_ATTENDEES, "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");
else
options.getFormatTemplates().add(MhtTemplateName.REQUIRED_ATTENDEES, "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");
};
msg.save(dataDir + "Meeting with Recurring Occurrences_out.mhtml", options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify From, To, HtmlBody, DeliveryNotificationOptions field
message.setFrom(new MailAddress("sender@sender.com"));
message.getTo().add("receiver@receiver.com");
message.setHtmlBody("<html><body>This is the Html body</body></html>");
message.setDeliveryNotificationOptions(DeliveryNotificationOptions.OnSuccess);
message.getHeaders().add("Return-Receipt-To", "sender@sender.com");
message.getHeaders().add("Disposition-Notification-To", "sender@sender.com");
// Create an instance of SmtpClient Class and Specify your mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
client.setHost("smtp.server.com");
client.setUsername("Username");
client.setPassword("Password");
client.setPort(25);
try
{
// Client.Send will send this message
client.send(message);
}
catch (Exception ex)
{
ex.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(RetrieveContentDescriptionInformationFromAttachmentHeaders.class) + "email/";
MailMessage msg = MailMessage.load(dataDir + "EmailWithAttachment.eml");
String description = msg.getAttachments().get_Item(0).getHeaders().get_Item("Content-Description");
System.out.println("Description: " + description);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(SaveMessageAsDraft.class) + "email/";
// Create a new instance of MailMessage class
MailMessage message = new MailMessage();
// Set sender information
message.setFrom(new MailAddress("from@domain.com", "Sender Name", false));
// Add recipients
message.getTo().addMailAddress(new MailAddress("to1@domain.com", "Recipient 1", false));
message.getTo().addMailAddress(new MailAddress("to2@domain.com", "Recipient 2", false));
// Set subject of the message
message.setSubject("New message created by Aspose.Email for Java");
// Set Html body of the message
message.setHtmlBody("<b>This line is in bold.</b> <br/> <br/>"
+ "<font color=blue>This line is in blue color</font>");
// Create an instance of MapiMessage and load the MailMessag instance into it
MapiMessage mapiMsg = MapiMessage.fromMailMessage(message);
// Set the MapiMessageFlags as UNSENT and FROMME
mapiMsg.setMessageFlags(MapiMessageFlags.MSGFLAG_UNSENT | MapiMessageFlags.MSGFLAG_FROMME);
// Save the MapiMessage to disk
mapiMsg.save(dataDir + "New-Draft.msg");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage eml = new MailMessage("test@from.to", "test@to.to", "template subject", "Template body");
String oftEmlFileName = "EmlAsOft_out.oft";
MsgSaveOptions options = SaveOptions.getDefaultMsgUnicode();
options.setSaveAsTemplate(true);
eml.save(dataDir + oftEmlFileName, options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Creates AlternateView to view an email message using the content specified in the //string
AlternateView alternate = AlternateView.createAlternateViewFromString("Alternate Text");
// Adding alternate text
message.getAlternateViews().addItem(alternate);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify HtmlBody
message.setHtmlBody("<html><body>This is the HTML body</body></html>");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = Utils.getSharedDataDir(ShowHideExtraPrintHeaders.class) + "email/";
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();
int options = MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.WriteCompleteEmailAddress;
mailFormatter.format(message, options);
if (!message.getHtmlBody().contains(pageHeader))
System.out.println("True");
else
System.out.println("False");
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String privateKeyFile = "key2.pem";
RSACryptoServiceProvider rsa = PemReader.getPrivateKey(privateKeyFile);
DKIMSignatureInfo signInfo = new DKIMSignatureInfo("test", "yandex.ru");
signInfo.getHeaders().addItem("From");
signInfo.getHeaders().addItem("Subject");
MailMessage mailMessage = new MailMessage("sender@gmail.com", "test@gmail.com");
mailMessage.setSubject("Signed DKIM message text body");
mailMessage.setBody("This is a text body signed DKIM message");
MailMessage signedMsg = mailMessage.dKIMSign(rsa, signInfo);
try
{
SmtpClient client = new SmtpClient("smtp.domain.com",25, "username", "password");
client.send(signedMsg);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify ReplyTo, from, To, Message subject and secret header field
message.getReplyToList().add("reply@reply.com");
message.setFrom(new MailAddress("sender@sender.com"));
message.getTo().add("receiver1@receiver.com");
message.setSubject("test mail");
message.getHeaders().add("secret-header", "mystery");
// Create an instance of SmtpClient Class and Specify your mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
client.setHost("smtp.server.com");
client.setUsername("Username");
client.setPassword("Password");
client.setPort(25);
try
{
// Client.Send will send this message
client.send(message);
}
catch (Exception ex)
{
ex.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
MailMessage message = new MailMessage();
// Specify From, To, HtmlBody, BodyEncoding field
message.setFrom(new MailAddress("sender@sender.com"));
message.getTo().add("receiver@receiver.com");
message.setHtmlBody("<html><body>This is the Html body</body></html>");
message.setBodyEncoding(Charset.forName("US-ASCII"));
// Create an instance of SmtpClient Class and Specify your mailing host server, Username, Password and Port
SmtpClient client = new SmtpClient();
client.setHost("smtp.server.com");
client.setUsername("Username");
client.setPassword("Password");
client.setPort(25);
try
{
// Client.Send will send this message
client.send(message);
}
catch (Exception ex)
{
ex.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Declare message as MailMessage instance
// Create an Instance of MailMessage class
MailMessage message = new MailMessage();
// Specify From address
message.setFrom(new MailAddress("sender@sender.com"));
// Specify recipients’ mail addresses
MailAddressCollection toList = new MailAddressCollection();
toList.add("receiver1@receiver.com");
toList.add("receiver2@receiver.com");
toList.add("receiver3@receiver.com");
message.setTo(toList);
// Specify CC addresses
MailAddressCollection ccList = new MailAddressCollection();
ccList.add("CC1@receiver.com");
ccList.add("CC2@receiver.com");
message.setCC(ccList);
// Specify BCC addresses
MailAddressCollection bccList = new MailAddressCollection();
bccList.add("Bcc1@receiver.com");
bccList.add("Bcc2@receiver.com");
message.setBcc(bccList);
// Create an instance of SmtpClient Class
SmtpClient client = new SmtpClient();
// Specify your mailing host server, Username, Password, Port
client.setHost("smtp.server.com");
client.setUsername("Username");
client.setPassword("Password");
client.setPort(25);
try
{
// Client.Send will send this message
client.send(message);
// Display ‘Message Sent’, only if message sent successfully
System.out.println("Message sent");
}
catch (Exception ex)
{
ex.printStackTrace();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String fileName = "MainMessage.eml";
String attachName = "barcode.png";
String outFileName = "test_out.eml";
FileInputStream fi = new FileInputStream(dataDir + attachName);
MailMessage eml = MailMessage.load(dataDir + fileName);
eml.getAttachments().addItem(new Attachment(fi, "barcode.png", "image/png"));
eml.save(dataDir + outFileName);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MsgLoadOptions msgLoadOptions = new MsgLoadOptions();
// The PreserveTnefAttachments option with MessageFormat.Msg will create the TNEF eml.
msgLoadOptions.setPreserveTnefAttachments(true);
MailMessage eml = MailMessage.load(dataDir + "test.eml", msgLoadOptions);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MapiMessage msg = MapiMessage.fromFile(dataDir + "Message.msg");
MailConversionOptions options = new MailConversionOptions();
options.setConvertAsTnef (true);
MailMessage mail = msg.toMailMessage(options);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
MailMessage mail = MailMessage.load(dataDir + "test.eml");
boolean isTnef = mail.getOriginalIsTnef();
System.out.println("isTnef: " + isTnef);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static void TestUpdateResources(String dataDir)
{
String fileName = dataDir + "tnefEMl1.eml";
String imgFileName = dataDir + "Untitled.jpg";
String outFileName = dataDir + "01_SAVE_Preserve_out.eml";
MailMessage originalMailMessage = MailMessage.load(fileName);
EmlLoadOptions emlOp = new EmlLoadOptions();
UpdateResources(originalMailMessage, imgFileName);
EmlSaveOptions emlSo = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSo.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);
originalMailMessage.save(outFileName, emlSo);
}
private static void UpdateResources(MailMessage msg, String imgFileName)
{
for (int i = 0; i < msg.getAttachments().size(); i++)
{
if (msg.getAttachments().get_Item(i).getContentType().getName().endsWith("jpg"))
{
try {
File attFile = new File(imgFileName);
msg.getAttachments().get_Item(i).setContentStream(new FileInputStream(attFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else if (msg.getAttachments().get_Item(i).getContentType().getName().endsWith("eml"))
{
ByteArrayOutputStream ms = new ByteArrayOutputStream();
msg.getAttachments().get_Item(i).save(ms);
//ms.reset();
ByteArrayInputStream ims = new ByteArrayInputStream(ms.toByteArray());
MailMessage embeddedMessage = MailMessage.load(ims);
UpdateResources(embeddedMessage, imgFileName);
ByteArrayOutputStream outProcessedEmbedded = new ByteArrayOutputStream();
embeddedMessage.save(outProcessedEmbedded, SaveOptions.getDefaultMsgUnicode());
//outProcessedEmbedded.reset();
ByteArrayInputStream inProcessedEmbedded = new ByteArrayInputStream(outProcessedEmbedded.toByteArray());
msg.getAttachments().get_Item(i).setContentStream(inProcessedEmbedded);
}
}
for (LinkedResource att : msg.getLinkedResources())
{
if (att.getContentType().getMediaType() == "image/jpg")
{
try {
File embeddedFile = new File(imgFileName);
FileInputStream es = null;
es = new FileInputStream(embeddedFile);
att.setContentStream(es );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create a new message
MailMessage message = new MailMessage();
message.setFrom(new MailAddress("sender@gmail.com"));
message.getTo().add("receiver@gmail.com");
message.setSubject("Using MailMessage Features");
// Specify message date
message.setDate(new Date());
// Specify message priority
message.setPriority(MailPriority.High);
// Specify message sensitivity
message.setSensitivity(MailSensitivity.Normal);
// Specify options for delivery notifications
message.setDeliveryNotificationOptions(DeliveryNotificationOptions.OnSuccess);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IEWSClient _client = EWSClient.getEWSClient("https://exchange.domain.com/ews/Exchange.asmx/", "user", "password", "");
//Create ExchangeMailboxInfo instance to save default mailbox info
ExchangeMailboxInfo mailbox = _client.getMailboxInfo();
//Declare ExchangeMessageInfoCollection instance for storing messages info collection
ExchangeMessageInfoCollection messages = null;
//Declare variable for getting specified custom folder URI
ExchangeFolderInfo subfolderInfo[] = new ExchangeFolderInfo[] { null };
//Check if specified custom folder exists
//PROBLEM: at this line
_client.folderExists(mailbox.getInboxUri(), "592633", subfolderInfo);
if (subfolderInfo != null) {
//Get all the messages info from the target URI
messages = _client.findMessages(subfolderInfo[0].getUri());
//Parse all the messages info collection
for (ExchangeMessageInfo info : messages) {
String strMessageURI = info.getUniqueUri();
// now get the message details using FetchMessage()
MailMessage msg = _client.fetchMessage(strMessageURI);
// display message details
System.out.println("Subject: " + msg.getSubject());
}
} /*else {
System.out.println("Target folder not found");
}*/
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IEWSClient client = EWSClient.getEWSClient("https://exchange.domain.com/ews/Exchange.asmx", "username", "password", "domain.com");
//Initialize MapiContact object and populate contact information
MapiContact contact = new MapiContact();
contact.setElectronicAddresses(null);
contact.setTelephones(null);
contact.setNameInfo(new MapiContactNamePropertySet("John", "", "Doe"));
//Create the contact on the Exchange server
client.createContact(contact);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String mailboxUri = "https://ex2010/ews/exchange.asmx";
String username = "test.exchange";
String password = "pwd";
String domain = "ex2010.local";
NetworkCredential credentials = new NetworkCredential(username, password, domain);
IEWSClient client = EWSClient.getEWSClient(mailboxUri, credentials);
//Create New Contact
Contact contact = new Contact();
//Set general info
contact.setGender(Gender.Male);
contact.setDisplayName("Frank Lin");
contact.setCompanyName("ABC Co.");
contact.setJobTitle("Executive Manager");
//Add Phone numbers
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.setNumber("123456789");
phoneNumber.setCategory(PhoneNumberCategory.getHome());
contact.getPhoneNumbers().add(phoneNumber);
//contact's associated persons
AssociatedPerson person = new AssociatedPerson();
person.setName("Catherine");
person.setCategory(AssociatedPersonCategory.getSpouse());
contact.getAssociatedPersons().add(person);
person = new AssociatedPerson();
person.setName("Bob");
person.setCategory(AssociatedPersonCategory.getChild());
contact.getAssociatedPersons().add(person);
person = new AssociatedPerson();
person.setName("Merry");
person.setCategory(AssociatedPersonCategory.getSister());
contact.getAssociatedPersons().add(person);
//URLs
Url url = new Url();
url.setCategory(UrlCategory.getBlog());
url.setHref("www.blog.com");
contact.getUrls().add(url);
url = new Url();
url.setCategory(UrlCategory.getHomePage());
url.setHref("www.homepage.com");
contact.getUrls().add(url);
//Set contact's Email address
EmailAddress address = new EmailAddress();
address.setAddress("Frank.Lin@Abc.com");
address.setDisplayName("Frank Lin");
address.setCategory(EmailAddressCategory.getCustom().getEmail1());
try
{
client.createContact(contact);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IEWSClient client = null;
try {
client = EWSClient.getEWSClient("https://outlook.office365.com/ews/exchange.asmx", "username", "password");
Calendar calendar = Calendar.getInstance();
Date startTime = calendar.getTime();
calendar.add(java.util.Calendar.HOUR, 1);
Date endTime = calendar.getTime();
String timeZone = "America/New_York";
Appointment appointment = new Appointment("Room 121", startTime, endTime,
MailAddress.to_MailAddress("email1@aspose.com"),
MailAddressCollection.to_MailAddressCollection("email2@aspose.com"));
appointment.setTimeZone(timeZone);
appointment.setSummary("EMAILNET-35198 - ".concat(java.util.UUID.randomUUID().toString()));
appointment.setDescription("EMAILNET-35198 Ability to add Java event to Secondary Calendar of Office 365");
// Create new calendar folder
client.createFolder(client.getMailboxInfo().getCalendarUri(), "new calendar", null, "IPF.Appointment");
ExchangeFolderInfoCollection calendarSubFolders = client.listSubFolders(client.getMailboxInfo().getCalendarUri());
String newCalendarFolderUri = calendarSubFolders.get_Item(0).getUri();
// Appointment API with calendar folder URI
// Create Appointment
client.createAppointment(appointment, newCalendarFolderUri);
// Update Appointment
appointment.setLocation("Room 122");
client.updateAppointment(appointment, newCalendarFolderUri);
// List Appointments
Appointment[] listAppointments = client.listAppointments(newCalendarFolderUri);
// List default calendar folder
listAppointments = client.listAppointments(client.getMailboxInfo().getCalendarUri());
// Cancel Appointment
client.cancelAppointment(appointment, newCalendarFolderUri);
listAppointments = client.listAppointments(newCalendarFolderUri);
// Appointment API with context current calendar folder URI
client.setCurrentCalendarFolderUri(newCalendarFolderUri);
// Create Appointment
client.createAppointment(appointment);
appointment.setLocation("Room 122");
// Update Appointment
client.updateAppointment(appointment);
// List Appointments
listAppointments = client.listAppointments();
// List default calendar folder
listAppointments = client.listAppointments(client.getMailboxInfo().getCalendarUri());
// Cancel Appointment
client.cancelAppointment(appointment);
listAppointments = client.listAppointments();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (client != null)
((IDisposable) client).dispose();
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IEWSClient client = EWSClient.getEWSClient("exchange.domain.com/ews/Exchange.asmx", "username", "password", "");
client.addHeader("X-AnchorMailbox", "username@domain.com");
ExchangeMessageInfoCollection messageInfoCol = client.listMessages(client.getMailboxInfo().getInboxUri());
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create instance of IEWSClient class by providing credentials
IEWSClient client = EWSClient.getEWSClient("https://exchange.domain.com/ews/Exchange.asmx/", "user", "password", "");
// Get Exchange mailbox info of other email account
ExchangeMailboxInfo mailboxInfo = client.getMailboxInfo();
ExchangeFolderInfo info = client.getFolderInfo(mailboxInfo.getInboxUri());
ExchangeFolderInfoCollection fc = new ExchangeFolderInfoCollection();
fc.addItem(info);
client.backup(fc, "Backup.pst", 0); //0 for None, 1 for Recursive
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
IEWSClient client = EWSClient.getEWSClient("https://exchange.domain.com/ews/Exchange.asmx", "username", "password", "domain.com");
// Create an appointment
MailAddressCollection attendees = new MailAddressCollection();
attendees.addItem(new MailAddress("attendee_address@aspose.com", "Attendee"));
SimpleDateFormat dateformat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String strStartTime = "02-04-2013 11:30:00";
Date startTime = dateformat.parse(strStartTime);
String strEndTime = "02-04-2013 12:30:00";
Date endTime = dateformat.parse(strEndTime);
Appointment app = new Appointment("Room 112", startTime, endTime, new MailAddress("organizeraspose-email.test3@domain.com"), attendees);
app.setTimeZone("GMT");
String uid = client.createAppointment(app);
// Update an appointment
Appointment fetchedAppointment1 = client.fetchAppointment(uid);
app.setLocation("Room 115");
app.setSummary("New summary for " + app.getSummary());
app.setDescription("New Description");
client.updateAppointment(app);
Appointment[] appointments1 = client.listAppointments();
System.out.println("Total Appointments: " + appointments1.length);
// Delete/Cancel an appointment
Appointment fetchedAppointment2 = client.fetchAppointment(uid);
System.out.println("Summary: " + fetchedAppointment2.getSummary());
System.out.println("Location: " + fetchedAppointment2.getLocation());
System.out.println("Description: " + fetchedAppointment2.getDescription());
client.cancelAppointment(app);
Appointment[] appointments2 = client.listAppointments();
System.out.println("Total Appointments: " + appointments2.length);
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static IEWSClient getEWSClient() {
IEWSClient client = EWSClient.getEWSClient("https://exchange.domain.com/ews/Exchange.asmx/", "user", "password", "");
return client;
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
public static ExchangeClient getExchangeClient() {
// Create instance of ExchangeClient class by giving credentials
ExchangeClient client = new ExchangeClient("http://MachineName/exchange/Username", "Username", "password", "domain");
return client;
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Connect to Exchange Server using ImapClient class
ImapClient imapClient = new ImapClient("imap.gmail.com", 993, "username", "password");
// Select the Inbox folder
imapClient.selectFolder(ImapFolderInfo.IN_BOX);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.listMessages();
for (ImapMessageInfo msgInfo : msgCollection) {
System.out.println(msgInfo.getSubject());
}
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient("imap.gmail.com", 993, "username", "password");
imapClient.selectFolder(ImapFolderInfo.IN_BOX);
// Get the list of messages
ImapMessageInfoCollection msgCollection = imapClient.listMessages();
for (ImapMessageInfo msgInfo : msgCollection) {
//Fetch the message from Inbox using its SequenceNumber from msgI