adding reciepeints for mail in java mail api program - java

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

Related

Unable to render outlook invitation on different email service providers

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.

Retrieving emails from Latest to oldest Java Mail API

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];

Java program throws exception if i add more participants in CC list

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

how to fix path manipulation and null deference issues for the following sample

I am getting the following issues after scanning the code using fortify....
1>path manipulation issue:
private MimeMessage prepareMessage(EmailMessage req) throws EmailProviderException {
long start=System.currentTimeMillis(),finish=0;
try {
MimeMessage message = emailSender.createMimeMessage();
// Create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
// Set email addresses
helper.setFrom(convertAddress(req.getFromAddress()));
helper.setTo(convertAddress(req.getToAddress()));
helper.setCc(convertAddress(req.getCcAddress()));
helper.setBcc(convertAddress(req.getBccAddress()));
// Set subject and body
helper.setSubject(req.getEmailSubject());
String emailBody = req.getEmailBody();
String emailMime = req.getEmailMimeType();
MimeBodyPart messagePart = new MimeBodyPart();
DataSource bodyDataSource = new ByteArrayDataSource(emailBody, emailMime);
messagePart.setDataHandler(new DataHandler(bodyDataSource));
helper.getMimeMultipart().addBodyPart(messagePart);
// Add attachments
List<EmailAttachment> lAttach = req.getEmailAttachment();
if (lAttach != null) {
for (EmailAttachment attachMnt: lAttach) {
DataSource dSource = new ByteArrayDataSource(attachMnt
.getContent(), attachMnt
.getMimeType());
helper.addAttachment(attachMnt.getFileName(), dSource);
}
}
finish=System.currentTimeMillis();
statsLogger.info(new FedExLogEntry("prepareMessage took {0}ms",new Object[]{finish-start}));
return message;
} catch (Exception e) {
// Covers MessagingException, IllegalStateException, IOException, MailException
String emsg = new StringBuilder("Unable to prepare smtp message.")
.append("\n").append(req.toString()).toString();
logger.warn(emsg, e);
throw new EmailProviderException(emsg, e);
}
}
Null dereference issues
issue 1.
public byte[] toByteArray(Notification nd) throws EmailProviderException {
String message = null;
try {
JAXBContext jc = JAXBContext.newInstance(nd.getClass());
if (jc != null) {
Marshaller m = jc.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(nd, sw);
message = sw.toString();
}
} catch (JAXBException e) {
throw new EmailProviderException("Unable to convert NDS notification to byte array.", e);
}
return message.getBytes();
}
null dereference issue 2..
private void addLastUpdatedHours(
List<LocationHoursForADate> masterHours, List<LocationHoursWithSearchedDate> hoursToAdd, Map<String,String> scheduleTypeIncludesMap){
String prevScheduleTypeCode = null;
String prevHourTypeCode = null;
Date searchedDate = null;
// Build map of locationHours to searchDates
List<LocationHours> locationHours = null;
Map<Date, List<LocationHours>> locationHoursSearchDatesMap = new HashMap<Date, List<LocationHours>>();
for(LocationHoursWithSearchedDate locationHoursWithSearchedDate : hoursToAdd) {
if(scheduleTypeIncludesMap.containsKey(locationHoursWithSearchedDate.getLocationHoursPK().getScheduleTypeCd())) {
searchedDate = locationHoursWithSearchedDate.getLocationHoursPK().getSearchedDate();
locationHours = locationHoursSearchDatesMap.get(searchedDate);
if(locationHours==null) {
locationHours = new ArrayList<LocationHours>();
locationHoursSearchDatesMap.put(searchedDate,locationHours);
}
locationHours.add(locationHoursWithSearchedDate.createLocationHours());
}
}
for(Map.Entry<Date,List<LocationHours>> entry : locationHoursSearchDatesMap.entrySet()) {
prevHourTypeCode = null;
prevScheduleTypeCode = null;
searchedDate = entry.getKey();
for(LocationHours hour: entry.getValue()){
// new ST & new 01, add it
if((prevScheduleTypeCode == null) && (prevHourTypeCode == null)){
masterHours.add(new LocationHoursForADate(searchedDate, hour));
prevScheduleTypeCode = hour.getLocationHoursPK().getScheduleTypeCd();
prevHourTypeCode = hour.getLocationHoursPK().getHoursTypeCd();
}
else{
//same ST
if(prevScheduleTypeCode.equals(hour.getLocationHoursPK().getScheduleTypeCd())){
// same 01, skip this schedule
if(prevHourTypeCode.equals(hour.getHoursType().getHoursTypeCd())){
continue;
}
else { //new 01, add it
masterHours.add(new LocationHoursForADate(searchedDate, hour));
prevScheduleTypeCode = hour.getLocationHoursPK().getScheduleTypeCd();
prevHourTypeCode = hour.getLocationHoursPK().getHoursTypeCd();
}
}
else{ //new ST, add it
masterHours.add(new LocationHoursForADate(searchedDate, hour));
prevScheduleTypeCode = hour.getLocationHoursPK().getScheduleTypeCd();
prevHourTypeCode = hour.getLocationHoursPK().getHoursTypeCd();
}
}
}
}
}
}
Well, the second case (null deference 1) is easy to spot.
The problem is that if there is an exception in the try-catch block then the object message will be null, so the final instruction return message.getBytes() will raise a NullPointerException.
One way to avoid it is changing the return statement like this:
return message != null ? message.getBytes() : null;
But maybe, you will prefer to raise the exception...

Java Receiving attachment mail error

I have a java code to get attachment using java mail and i'm able to download the attachment and inserting into specific folder. But the problem is when i'm sending email with attachment from Blackberry phone i get error as follows for downloading the attachment.
ERROR [STDERR] java.io.FileNotFoundException: E:\CCjboss\server\sor
emicc\deploy\eis.ear\CC.war\attachment\=?utf-8?B?MS5qcGc= (The filename, directo
ry name, or volume label syntax is incorrect)
07:31:10,739 ERROR [STDERR] at java.io.FileOutputStream.open(Native Method)
07:31:10,741 ERROR [STDERR] at java.io.FileOutputStream.<init>(FileOutputStr
eam.java:179)
07:31:10,744 ERROR [STDERR] at java.io.FileOutputStream.<init>(FileOutputStr
eam.java:131)
07:31:10,747 ERROR [STDERR] at com.infosense.eis.webapp.util.Mobilekiran.sav
eFile(Mobilekiran.java:230)
07:31:10,750 ERROR [STDERR] at com.infosense.eis.webapp.util.Mobilekiran.Mob
ileTimeCheckTask(Mobilekiran.java:179)
07:31:10,753 ERROR [STDERR] at com.infosense.eis.webapp.util.Mobilekiran.run
(Mobilekiran.java:38)
07:31:10,756 ERROR [STDERR] at java.util.TimerThread.mainLoop(Timer.java:432
)
07:31:10,759 ERROR [STDERR] at java.util.TimerThread.run(Timer.java:382)
I think its with some encoding and decoding problem. Attachment get encoded or something
=?utf-8?B?MS5qcGc=
The below is the code to receive a email with attachment
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import java.util.*;
import java.lang.String;
import javax.mail.internet.*;
/**
*
* #author Administrator
*/
public class Mobilekiran extends TimerTask{
List emattach=new ArrayList();
List emails = new ArrayList();
List attachments=new ArrayList();
String emailbody=null;
String bodypart=null;
String s1=null;
String fromaddress=null;
String subject=null;
String body=null;
String date1=null;
String filename=null;
int filesize=0;
public void run() {
MobileTimeCheckTask();
}
private void MobileTimeCheckTask(){
String host = "mail.**********.com";
String username = "*****#****.com";
String password = "*******";
String downloadDir = "E:/CCjboss/server/soremicc/deploy/eis.ear/CC.war/attachment";
String provider = "pop3";
try{
// Create empty properties
Properties props = new Properties();
// Get the session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore("pop3");
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message messages[] = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
// from
Address[] toaddress1=messages[i].getAllRecipients();
String toaddress=toaddress1[0].toString();
System.out.println("to address"+toaddress1[0].toString());
emails.add(0,messages[i].getFrom()[0].toString());
s1=messages[i].getFrom()[0].toString();
InternetAddress address = new InternetAddress(s1);
fromaddress=address.getAddress();
// subject
emails.add(1,messages[i].getSubject());
subject=messages[i].getSubject();
// received date
if (messages[i].getReceivedDate() != null) {
emails.add(2,messages[i].getReceivedDate().toString());
date1=messages[i].getReceivedDate().toString();
// emattach.add(0,emails);
} else {
emails.add(2,new Date());
date1=(new Date()).toString();
// emattach.add(0,emails);
}
// body and attachments
//email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String) {
emails.add(3,(String) content);
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
boolean d=true;
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
BodyPart bp=mp.getBodyPart(j);
Object o2 = bp.getContent();
if (o2 instanceof String) {
System.out.println("**This is a String BodyPart**");
System.out.println("bodypart "+(String)o2);
if(d)
emails.add(3,(String)o2);
body=(String)o2;
d=false;
}
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
// Plain
emailbody += (String) mbp.getContent();
emails.add(3,emailbody);
}
} else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition .equals(Part.INLINE))) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain")) {
emailbody += (String) mbp.getContent();
emails.add(3,emailbody);
} else {
//EmailAttachment attachment = new EmailAttachment();
System.out.println("the filename i required"+part.getFileName().toString());
attachments.add(0,Mobilekiran.decodeName(part.getFileName()));
filename=decodeName(part.getFileName());
File savedir = new File(downloadDir);
savedir.mkdirs();
// File savefile = File.createTempFile( "emailattach", ".atch", savedir);
File savefile = new File(downloadDir,attachments.get(0).toString());
attachments.add(1,savefile.getAbsolutePath());
attachments.add(2,new Integer(Mobilekiran.saveFile(savefile, part)));
filesize=saveFile(savefile,part);
emattach.add(0,attachments);
}
}
} // end of multipart for loop
emattach.add(0,emails);
System.out.println(emattach);
emattach.clear();
System.out.println(emattach);
messages[i].setFlag(Flags.Flag.DELETED , true);
} // end messages for loop
// Finally delete the message from the server.
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages
store.close();
}catch(Exception e){
e.printStackTrace();
}
}
private static String decodeName(String name) throws Exception {
if (name == null || name.length() == 0) {
return "unknown";
}
String ret = java.net.URLDecoder.decode(name, "UTF-8");
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
private static int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(saveFile));
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while ((ret = is.read(buff)) > 0) {
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
}
Please help me out in solving the above problem.
Looks like the attachment is encoded.

Categories

Resources