I am sending an outlook invitation using java mail to four different email servers:
web.de
gmx.net
gmail.com
company's private email server (which is configured on outlook)
The invitation is rendered/previewed on gmail only but we need to render/preview it on every platform.
My main class is
public class Email {
// Constants for the ICalendar methods.
public static final String METHOD_CANCEL = "CANCEL";
public static final String METHOD_PUBLISH = "PUBLISH";
public static final String METHOD_REQUEST = "REQUEST";
// Apply this organizer, if no organizer is given.
private static final String DEFAULT_ORGANIZER = "zain#company.com";
// Common ICalendar fields.
private String method;
private Calendar beginDate;
private Calendar endDate;
private String location;
private int uid;
private String description;
private String subject;
private String organizer;
/*
* #param args
*/
public static void main(String[] args) {
try {
Email email = new Email();
email.send();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
public void send() throws Exception {
try {
String from = "mansoor#company.com";
Properties prop = new Properties();
Address[] receivers = new InternetAddress[] {
new InternetAddress("abc#company.com")
, new InternetAddress("abc#gmail.com")
, new InternetAddress("abc#web.de")
, new InternetAddress("abc#gmx.de")
};
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.host", "smtp.company.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("smtp#company.com", "password");
}
};
Session session = Session.getDefaultInstance(prop, authenticator);
// Define message
MimeMessage message = new MimeMessage(session);
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=VEVENT");
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, receivers);
message.setSubject("Outlook Meeting Request Using JavaMail");
this.subject = "Meeting Request Test Subject";
this.description = "PLEASE IGNORE THIS MAIL AS IT IS A TEST.";
this.beginDate = new GregorianCalendar(2018, 07-01, 17, 19, 00);
this.endDate = new GregorianCalendar(2018, 07-01, 17, 19, 45);
this.method = Email.METHOD_REQUEST;
this.location = "Office # 13";
// Create the calendar part
BodyPart calendarPart = new MimeBodyPart();
// Fill the message
calendarPart.setHeader("Content-Class", "urn:content- classes:calendarmessage");
calendarPart.setHeader("Content-ID", "calendar_message");
calendarPart.setHeader("Content-Disposition", "inline;filename=Test_invite1.ics");
calendarPart.setFileName("Test_invite1");
calendarPart.setDataHandler(
new DataHandler(
new ByteArrayDataSource(createMessage(), "text/calendar")));// very important
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(calendarPart);
// Put parts in message
message.setContent(multipart);
// send message
Transport.send(message);
for(Address receiver: receivers){
System.out.println(receiver);
}
} catch (MessagingException me) {
System.out.println("Failed sending email");
me.printStackTrace();
} catch (Exception ex) {
System.out.println("Failed sending email");
ex.printStackTrace();
} finally {
System.out.println("End sending email");
System.exit(0);
}
}
public String createMessage() {
// Create the proper date format string required by the ICalendar spec.
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
final String stringBeginDate = formatter.format(beginDate.getTime());
final String stringEndDate = formatter.format(endDate.getTime());
// Encode the description => mark new lines.
final String encodedDescription = description.replaceAll("\r\n", "\\\\n");
// Use the default organizer if none is given.
if (this.organizer == null) {
this.organizer = DEFAULT_ORGANIZER;
}
// Content string as array.
String[] contents = {
"BEGIN:VCALENDAR",
"METHOD:" + this.method,
"BEGIN:VEVENT",
"UID:" + this.uid,
"DTSTART:" + stringBeginDate,
"DTEND:" + stringEndDate,
"LOCATION:" + this.location,
"DESCRIPTION:" + encodedDescription,
"ATTENDEE;RSVP=TRUE:MAILTO:" + this.organizer,
"ORGANIZER:" + this.organizer,
"SUMMARY:" + this.subject,
"END:VEVENT",
"END:VCALENDAR"
};
// Build a well-formatted string from the array.
StringBuilder sb = new StringBuilder();
for (String line : contents) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
return sb.toString();
}
}
Please add comment if you have any ambiguity before down voting. I have seen so many question on stackoverflow.com but found no proper solution.
Related
I am new in MQTT world. I have written a code to subscribe a topic and get message from topic and store it in database. Now my problem is how to put this code on server so that it will keep receiving message infinitely. I am trying to create a scheduler but in that case i am Getting Persistence Already in Use error from MQTT. I cannot change the clientId every time it connect. It is a fixed one in my case. Is there any way to get the persistence object which is already connected for a particular clientId?
Please help. Thanks and advance.
Please Find the code subscribe topic and messageArrived method of mqqt to get message from topic
public class AppTest {
private MqttHandler handler;
public void doApp() {
// Read properties from the conf file
Properties props = MqttUtil.readProperties("MyData/app.conf");
String org = props.getProperty("org");
String id = props.getProperty("appid");
String authmethod = props.getProperty("key");
String authtoken = props.getProperty("token");
// isSSL property
String sslStr = props.getProperty("isSSL");
boolean isSSL = false;
if (sslStr.equals("T")) {
isSSL = true;
}
// Format: a:<orgid>:<app-id>
String clientId = "a:" + org + ":" + id;
String serverHost = org + MqttUtil.SERVER_SUFFIX;
handler = new AppMqttHandler();
handler.connect(serverHost, clientId, authmethod, authtoken, isSSL);
// Subscribe Device Events
// iot-2/type/<type-id>/id/<device-id>/evt/<event-id>/fmt/<format-id>
handler.subscribe("iot-2/type/" + MqttUtil.DEFAULT_DEVICE_TYPE
+ "/id/+/evt/" + MqttUtil.DEFAULT_EVENT_ID + "/fmt/json", 0);
}
/**
* This class implements as the application MqttHandler
*
*/
private class AppMqttHandler extends MqttHandler {
// Pattern to check whether the events comes from a device for an event
Pattern pattern = Pattern.compile("iot-2/type/"
+ MqttUtil.DEFAULT_DEVICE_TYPE + "/id/(.+)/evt/"
+ MqttUtil.DEFAULT_EVENT_ID + "/fmt/json");
DatabaseHelper dbHelper = new DatabaseHelper();
/**
* Once a subscribed message is received
*/
#Override
public void messageArrived(String topic, MqttMessage mqttMessage)
throws Exception {
super.messageArrived(topic, mqttMessage);
Matcher matcher = pattern.matcher(topic);
if (matcher.matches()) {
String payload = new String(mqttMessage.getPayload());
// Parse the payload in Json Format
JSONObject contObj = new JSONObject(payload);
System.out
.println("jsonObject arrived in AppTest : " + contObj);
// Call method to insert data in database
dbHelper.insertIntoDB(contObj);
}
}
}
Code to connect to client
public void connect(String serverHost, String clientId, String authmethod,
String authtoken, boolean isSSL) {
// check if client is already connected
if (!isMqttConnected()) {
String connectionUri = null;
//tcp://<org-id>.messaging.internetofthings.ibmcloud.com:1883
//ssl://<org-id>.messaging.internetofthings.ibmcloud.com:8883
if (isSSL) {
connectionUri = "ssl://" + serverHost + ":" + DEFAULT_SSL_PORT;
} else {
connectionUri = "tcp://" + serverHost + ":" + DEFAULT_TCP_PORT;
}
if (client != null) {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
client = null;
}
try {
client = new MqttClient(connectionUri, clientId);
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(this);
// create MqttConnectOptions and set the clean session flag
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(authmethod);
options.setPassword(authtoken.toCharArray());
//If SSL is used, do not forget to use TLSv1.2
if (isSSL) {
java.util.Properties sslClientProps = new java.util.Properties();
sslClientProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
options.setSSLProperties(sslClientProps);
}
try {
// connect
client.connect(options);
System.out.println("Connected to " + connectionUri);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public class testemail {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "xxx#gmail.com"; //
private String password = "xxx";
public testemail() {
}
public void readMails() throws Exception {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
System.out.println("Number of mails = " + messages.length);
for ( Message message : messages ) {
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
Object content = message.getContent();
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
System.out.println("--------------------------------");
}
inbox.close(true);
store.close();
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) throws Exception {
int multiPartCount = content.getCount();
for (int i = 0; i < multiPartCount; i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof Multipart) {
procesMultiPart((Multipart) o);
}
}
}
public static void main(String[] args) throws Exception {
testemail sample = new testemail();
sample.readMails();
}}
In the above code I am able to get emails from oldest to newest on my console from gmail. However I would want it to loop from newest to oldest. Is there any way I could get this achieved. Please Help :)
I don't think there's a parameter or method for this in the JavaMail API. You have to reverse the messages array yourself, e.g. by including the Commons.Lang library:
messages = ArrayUtils.reverse(messages);
or iterating over it in the other direction:
for (int i = messages.length - 1; i >= 0; i--) {
Message message = messages[i];
I have developed a below program to send the mail using java ail api , now it through error if i add more than one recipient in cc can you please advise how can i customise my below program so that i can add more people in cc , shall i go for an array for cc feild .
public class abctest{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String mailSmtpHost = "66.66.66.66;
String mailSmtpPort = "1789" ;
String mailTo = "ert#abc.com";
String mailCc = "ewq#abc.com "; // ******throws exception if i add more than one email in cc list
String mailFrom = "rrr#abc.com";
String mailSubject = "Test Email from Java";
String mailText = "This is an email for Brokerage from Java";
sendEmail(mailTo, mailCc, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String cc, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
Session emailSession = Session.getDefaultInstance(properties);
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
emailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setText(text);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You can use
emailMessage.addRecipients(Message.RecipientType.CC,
InternetAddress.parse("eranda#mahesh.com, mahesh#eranda.com"));
or
Address[] cc = new Address[] {new InternetAddress("eranda#mahesh.com"),
new InternetAddress("mahesh#eranda.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
I have created the method in class named A as shown below which functionality is to send the mails using java mail api , now the bellow method accepts the parameters now my query is that how should i add recipients in an array as the recipients must be of array type that is passes please advise
class A
{
public boolean postMail(String recipients[], String subject, String message, String from) throws Exception {
boolean debug = true;
boolean result = false;
// create a message
try {
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
this.mimeMessage.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int index = 0; index < recipients.length; index++) {
addressTo[index] = new InternetAddress(recipients[index]);
}
this.mimeMessage.setRecipients(Message.RecipientType.BCC, addressTo);
this.mimeMessage.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
this.mimeMessage.setSubject(subject);
this.mimeMessage.setContent(message, "text/html");
Transport.send(this.mimeMessage);
result = true;
} catch (MessagingException messagingException) {
result = false;
messagingException.printStackTrace();
// throw new CASSException(messagingException);
}
return result;
}
}
now my query is that i am trying to invoke this method from within the class shown below '
class A
{
String Subject = "testmailsubject";
String message = "simple test message";
String from ="test#abc.com";
A a1 = new A ();
a1.postMail
//***********method *************
public boolean postMail(String recipients[], String subject, String message, String from) throws Exception {
boolean debug = true;
boolean result = false;
// create a message
try {
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
this.mimeMessage.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int index = 0; index < recipients.length; index++) {
addressTo[index] = new InternetAddress(recipients[index]);
}
this.mimeMessage.setRecipients(Message.RecipientType.BCC, addressTo);
this.mimeMessage.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
this.mimeMessage.setSubject(subject);
this.mimeMessage.setContent(message, "text/html");
Transport.send(this.mimeMessage);
result = true;
} catch (MessagingException messagingException) {
result = false;
messagingException.printStackTrace();
// throw new CASSException(messagingException);
}
return result;
}
}
Add Receipeints like this
Address[] TO = new Address[] {InternetAddress.parse("karthik#cherukuri.com"),
InternetAddress.parse("karthik2#cherukuri.com"),
InternetAddress.parse("karthik3#cherukuri.com")};
message.addRecipients(Message.RecipientType.TO, TO);
else if you want to send recipient array directly to method just initialize it email list you wanted.
String Subject = "testmailsubject";
String message = "simple test message";
String from ="test#abc.com";
String[] recipient = new String[]{"karthik#cherukuri.com","karthik2#cherukuri.com", "karthik3#cherukuri.com"};
a1.postmail(recipient,subject,from,message);
Attachments need to be added like this
MailMessage.addAttachment(File file, [String fileName])
, but innerly it seems that fileName is only used for MimeBodyPart.setFileName()
I dont find anyway to use the
MimeBodyPart.setContentID("myID") or MimeBodyPart.setHeader("Content-ID", "myID");
feature, so I can use images embeded in mail with
<img src='CID:MyID'>
It seems MailEngine is in the portal jar so only for internal use, and I was not able to find a solution for MailServiceUtil. Does it mean I need to decode all Liferay high-level API stuff from scratch and use Java Mail API?
I don't think there's a way to do that with Liferay (at least not at version 6.2). But I made it work with standard Java approach. The following is pretty similar to Liferay interface.
public void send(TemplateEmailerMailMessage mailMessage) throws UnsupportedEncodingException {
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailMessage.getFromEmail(), mailMessage.getFromName()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailMessage.getTo()));
message.setSubject(mailMessage.getSubject());
if (mailMessage.isHtmlFormat()) {
message.setText(mailMessage.getBody(), "text/html");
} else {
message.setText(mailMessage.getBody());
}
// create container for attachments and body parts
Multipart multipart = new MimeMultipart();
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getBody(), "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
// add attachments one by one
for (File file : mailMessage.getFileAttachments()) {
BodyPart messageAttachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageAttachmentPart.setDataHandler(new DataHandler(source));
messageAttachmentPart.setFileName(file.getName());
// set Content-ID so it is recognized by <img src="cid: ... ">
messageAttachmentPart.setHeader("Content-ID", "<" + file.getName() + ">");
multipart.addBodyPart(messageAttachmentPart);
}
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
The message object
public class TemplateEmailerMailMessage {
private String fromEmail;
private String fromName;
private String to;
private String body;
private String subject;
private boolean htmlFormat;
private List<File> fileAttachments = new ArrayList<>();
public void addAttachment(File file) {
fileAttachments.add(file);
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public boolean isHtmlFormat() {
return htmlFormat;
}
public void setHtmlFormat(boolean htmlFormat) {
this.htmlFormat = htmlFormat;
}
public List<File> getFileAttachments() {
return fileAttachments;
}
public void setFileAttachments(List<File> fileAttachments) {
this.fileAttachments = fileAttachments;
}
public String getFromEmail() {
return fromEmail;
}
public void setFromEmail(String fromEmail) {
this.fromEmail = fromEmail;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public void setFrom(String fromEmail, String fromName) {
this.fromEmail = fromEmail;
this.fromName = fromName;
}
}