I am adding custom header while sending email in Java. If anybody gives reply to that email I need to store the content of that email in database. I might receive multiple reply for that mail. So for identification I am adding custom header with unique value.
While reading unread email from inbox folder from imaps store, I am unable to read custom header. Other than custom header I am able to read other header.
I am reading email using below Class
public class OutLookReader_imaps {
Folder inbox;
public OutLookReader_imaps() throws IOException {
System.out.println("Inside MailReader()...");
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.host", "outlook.office365.com");
try {
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "example#entransys.com", "password");
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message messages[] = inbox.search(unseenFlagTerm);
if (messages.length == 0) System.out.println("No messages found.");
System.out.println("No. of Unread Messages : " + inbox.getUnreadMessageCount());
System.out.println("No. of Messages : " + inbox.getMessageCount());
System.out.println("No. of Deleted Messages : " + inbox.getMode());
for (int i = 0; i < messages.length; i++) {
if (i > 10) {
System.exit(0);
inbox.close(true);
store.close();
}
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
System.out.println("Sent Date : " + messages[i].getSentDate());
System.out.println("Header : " + messages[i].getAllHeaders());
System.out.println("Content : " + messages[i].getContent().toString());
System.out.println("Content Type : " + messages[i].getContentType());
System.out.println("Description : " + messages[i].getDescription());messages[i].getContent());
System.out.println("Unique Header : " + messages[i].getHeader("X-Universally-Unique-Identifier"));
System.out.println("Header uni : " + messages[i].getHeader("X-Uniform-Type-Identifier"));
Enumeration allHeaders = messages[i].getAllHeaders();
while (allHeaders.hasMoreElements()) {
Header header = (Header) allHeaders.nextElement();
String headerName = header.getName();
String headerVal = header.getValue();
System.out.println("Header Name : " + headerName);
System.out.println("Header Value : " + headerVal);
}
}
try {
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (MessagingException e) {
System.out.println("Exception while connecting to server: " + e.getLocalizedMessage());
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception {
for (int i = 0; i < msgs.length; i++) {
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception {
Address[] a;
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("Email From : " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
Date sentDate = message.getSentDate();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Email Subject : " + subject);
if (receivedDate != null) {
System.out.println("Received Date: " + df.format(receivedDate));
}
System.out.println("Sent Date : " + df.format(sentDate));
}
public static void main(String args[]) throws IOException {
new OutLookReader_imaps();
}
}
Custom headers that you add to messages you send will not be added to messages that reply to the message you sent. There will usually be an In-Reply-To header or References header that includes the Message-ID of the message you sent, but even those are not guaranteed to be present. The most reliable way of associating replies with sent messages is probably to include a unique ID in the Subject of the message you sent.
Related
I am Downloading Image from Gmail, what the problem here is , Image file upto 6MB, So it will take some more time in order to complete its download process. So my Question is Shall i compress image while downloading(ie Before save into path)? I have looked some Image compression examples in java,but all are taking image from one path then compress and finally stores that compressed image into some other folder.
If you want code for download attachment from gmail, Please click here . Could you please help me out to find the solution?
/*Downloading EmailAttachment into localfolder*/
public void downloadEmailAttachments(String protocol, String host, String port, String userName, String password,
String tempDirectory,String saveDirectory,String MessageID,String HeaderID,String emailDate,String emailSubject, MessageContext context) {
logger.info("===Inside downloadEmailAttachments Process====");
Properties properties = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(properties);
int status = 0;
try {
Store store = session.getStore(protocol);
store.connect(userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
logger.info("No of Unread Messages : " + folderInbox.getUnreadMessageCount());
/* create a search term for all "unseen" messages*/
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
SearchTerm searchTerm = new AndTerm(new MessageIDTerm(HeaderID), new SubjectTerm(emailSubject));
Message[] arrayMessages = folderInbox.search(searchTerm);
if(arrayMessages != null && arrayMessages.length > 0){
Message message = arrayMessages[0];
Address[] fromAddress = message.getFrom();
String msgId=mimeMessage.getMessageID();*/
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
String modifiedsubject=subject.toUpperCase().replaceAll("\\s+", "");
String attachmentname = "";
if(modifiedsubject.contains("SELLMYCAR")){
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
//String fileName = part.getFileName();
// part.setFileName(ESBMessageID+":"+new Date());
// String fileName = part.getFileName()+":"+ESBMessageID+":"+new Date();
String fileName = part.getFileName();
fileName=fileName.substring(0, fileName.lastIndexOf(".")).concat(".jpg");
System.out.println("Modified FileName:" + fileName);
attachmentname = fileName;
/*part.saveFile(saveDirectory + File.separator + fileName);*/
part.saveFile(tempDirectory + File.separator + fileName);
logger.info("Files are downloaded into "+ tempDirectory+" successfully");
if (attachmentname.length() > 1) {
attachmentname = attachmentname.substring(0, attachmentname.length());
}
/*FileMove Process*/
moveFile(tempDirectory,fileName,saveDirectory,MessageID,context);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
// print out details of each message
logger.info("Message # :");
logger.info("\t From: " + from);
//logger.info("\t UserName: " + name);
logger.info("\t Subject: " + subject);
logger.info("\t Sent Date: " + sentDate);
//logger.info("\t UserMailID: " + email);
logger.info("\t Attachments: " + attachmentname);
logger.info("\t LocalDownloadpath: " + saveDirectory);
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
}
}
// disconnect
folderInbox.close(false);
store.close();
} catch (MessagingException ex) {
logger.info("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}````
i Need To Verify Email is Received or not in gmail. So That i Tried The Following Code. But i Didn't Get The Result. Can You Please Sort Me out This.
The Following Code is :
public static void getPassword(String email, String password) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", email, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
Message[] messages = null;
boolean isMailFound = false;
Message mailFromProx = null;
// Search for mail from Prox with Subject = 'Email varification Testcase'
for (int i = 0; i <= 5; i++) {
messages = folder.search(new SubjectTerm("Email varification Testcase"), folder.getMessages());
// Wait for 20 seconds
if (messages.length == 0) {
Thread.sleep(20000);
}
}
// Search for unread mail
// This is to avoid using the mail for which
// Registration is already done
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
mailFromProx = mail;
System.out.println("Message Count is: " + mailFromProx.getMessageNumber());
isMailFound = true;
}
}
// Test fails if no unread mail was found
if (!isMailFound) {
throw new Exception("Could not find new mail from iGotThis :-(");
// Read the content of mail and get password
} else {
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(mailFromProx.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
System.out.println(buffer);
String result = buffer.toString().substring(buffer.toString().indexOf("is:") + 1,
buffer.toString().indexOf("3. Start enjoying an easier life!"));
String resultxx = result.substring(4, result.length() - 1);
//Print passsword
System.out.println(resultxx);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(Constant.Path_UserPassFile);
// set the properties value in property file
prop.setProperty("User_Password", resultxx);
PropsUtils.setProperties().setProperty("User_Password", resultxx);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Password = " + prop.getProperty("User_Password"));
}
}
}
i Tried Searching Lot of Results , But Nothing Not Clear. Can You Please Provide Me Prefect Result.
if You Got Any Results Regarding The Mail Testing in Selenium Please Provide Here , Let Me Try Here.
Here is the working solution for your problem. It uses JAVAX MAIL API and JAVA code.
It does a lot more, so remove the code that u don't need.
public GmailUtils(String username, String password, String server, EmailFolder
emailFolder) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.mime.base64.ignoreerrors", "true");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", 993, "<your email>", "<your password>");
Folder folder = store.getFolder(emailFolder.getText());
folder.open(Folder.READ_WRITE);
System.out.println("Total Messages:" + folder.getMessageCount());
System.out.println("Unread Messages:" + folder.getUnreadMessageCount());
messages = folder.getMessages();
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
System.out.println("***************************************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
System.out.println("Has Attachments: " + hasAttachments(mail));
}
}
}
public boolean hasAttachments(Message email) throws Exception {
// suppose 'message' is an object of type Message
String contentType = email.getContentType();
System.out.println(contentType);
if (contentType.toLowerCase().contains("multipart/mixed")) {
// this message must contain attachment
Multipart multiPart = (Multipart) email.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("Attached filename is:" + part.getFileName());
MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
String fileName = mimeBodyPart.getFileName();
String destFilePath = System.getProperty("user.dir") + "\\Resources\\";
File fileToSave = new File(fileName);
mimeBodyPart.saveFile(destFilePath + fileToSave);
// download the pdf file in the resource folder to be read by PDFUTIL api.
PDFUtil pdfUtil = new PDFUtil();
String pdfContent = pdfUtil.getText(destFilePath + fileToSave);
System.out.println("******---------------********");
System.out.println("\n");
System.out.println("Started reading the pdfContent of the attachment:==");
System.out.println(pdfContent);
System.out.println("\n");
System.out.println("******---------------********");
Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
Files.delete(fileToDeletePath);
}
}
return true;
}
return false;
}
public String getEmailBody(Message email) throws IOException, MessagingException {
String line, emailContentEncoded;
StringBuffer bufferEmailContentEncoded = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
while ((line = reader.readLine()) != null) {
bufferEmailContentEncoded.append(line);
}
System.out.println("**************************************************");
System.out.println(bufferEmailContentEncoded);
System.out.println("**************************************************");
emailContentEncoded = bufferEmailContentEncoded.toString();
if (email.getContentType().toLowerCase().contains("multipart/related")) {
emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
System.out.println(emailContentEncoded);
String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
return emailContentDecoded;
}
return emailContentEncoded;
}
I would suggest you to use Nada email api which are disposable email addresses and very easy to get the content.
Check the examples here.
http://www.testautomationguru.com/selenium-webdriver-email-validation-with-disposable-email-addresses/
I'm using javax.mail, IMAP provider and want to get number of recipients.
My email message has 3 recipients, but
System.out.println("AllRecipients: " + message.getAllRecipients().length);
and
System.out.println("Recipients: " + message.getRecipients(Message.RecipientType.TO).length);
returns value = 1.
Code:
public void checkEmail() throws MessagingException
{
String host = "imap.example.host";
Integer port = 993;
String username = "exampleLogin";
String password = "examplePassword";
String provider = "imaps";
String folderMail = "inbox";
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.socketFactory.port", port);
properties.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.imap.auth", "true");
properties.put("mail.imap.port", port);
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator(){protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("username","password");
}
});
Store store = session.getStore(provider);
store.connect(host, port, username, password);
try
{
Folder folder = store.getFolder(folderMail);
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages();
System.out.println("messages in folder: " + messages.length);
for (int messageNumber = 0, messageCount = messages.length; messageNumber < messageCount; messageNumber ++)
{
Message message = messages[messageNumber];
System.out.println("---------------------------------");
System.out.println("Email #: " + messageNumber);
System.out.println("Subject: " + message.getSubject());
System.out.println("AllRecipients: " + message.getAllRecipients().length);
}
folder.close(false);
}
catch (FolderNotFoundException e)
{
System.out.println(System.currentTimeMillis() + " :: Folder " + folderMail + " not found or empty");
}
System.out.println("FINISH");
}
can anyone help?
I am trying to read my messages, I can get it to print the header but the from and the content are displayed funny.
Here is the code I am using to display the messages:
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
The output is as follows:
Message 1:
From: [javax.mail.internet.InternetAddress;#175831e]
Subject: Hello //This is correct
Body: javax.mail.internet.MimeMultipart#15b5219
Why doesn't this print out the actual email address for the from statement? And why doesn't it print out the actual body content? (I am only interesting in the plain text.)
Whole code:
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.util.*;
import com.sun.mail.imap.*;
import java.io.*;
public class MailClient {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("mail.store.protocol","imaps");
Session session;
session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","email#gmail.com","password");
IMAPFolder folder = (IMAPFolder) store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen,false);
Message message[] = folder.search(unseenFlagTerm);
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
System.out.println(newMsg);
folder.close(false);
store.close();
}
catch (MessagingException e) {
System.out.println("Error: " + e);
}
}
}
Thanks!
For plain text and html messages:
String content= messages[i].getContent().toString();
For Multipart Messages:
Multipart multipart = (Multipart) messages[i].getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) { // BodyPart.ATTACHMENT doesn't work for gmail
System.out.println("Mail have some attachment");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
}
else {
System.out.println("Body: "+bodyPart.getContent());
content= bodyPart.getContent().toString();
}
The JavaMail FAQ tells you how to access the main text body of a message.
change this
message[i].getFrom()
to
message[i].getFrom()[0].toString())
Try to use next:
message[i].writeTo(System.out);
i know how can we retrive the mails from INBOX folder...but now i want to retrieve mails from SENT ITEMS folder...i am using imap to retrieve the data...
Let me know what parameter i should pass in this function to get mails from SENT ITEMS folder
Folder folder=store.getFolder("inbox");i should change the inbox as some stirng i want to know that string...
There is not a standard name here. The IMAP spec requires that the inbox be called "INBOX", but no other folders are specifically defined. It's just a name of a folder after all - some providers will use "Sent", some will use "Sent Items" and you might even see some other variants about.
I'd recommend listing the folders that the server knows about, and selecting the appropriate one from there (either interactively, or perhaps grepping for "sent" in the name if running headless). A better option overall might be to make this a configurable parameter (if your application already has a properties file).
Of course, if this is a throwaway project you could just hard-code the value for the specific server in question. But if you want to do it properly, you'll need to be flexible.
I found the solution for my problem....
i used this code to list out the folders from mail server
and pass those values in getFolder() function...it's working fine..
Folder[] folderList = store.getDefaultFolder().list();
for (int i = 0; i < folderList.length; i++) {
System.out.println(folderList[i].getFullName());
}
Gmail stores sent mails under a folder called Sent Mail inside [Gmail] folder. So I was able to get the sent mail folder through this;
Folder sentMail = store.getFolder( "[Gmail]" ).getFolder( "Sent Mail" );
This code will retrieve all mails and will print the contents and store in local if have any attachment
public class MailReader {
Folder inbox;
public MailReader() {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "username",
"password");
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : "
+ inbox.getMessageCount() + " "
+ inbox.getUnreadMessageCount());
/* Open the inbox using store. */
inbox.open(Folder.READ_ONLY);
/*
* Get the messages which is unread in the Inbox Message messages[]
* = inbox.search(new FlagTerm( new Flags(Flag.SEEN), false));
*/
Message messages[] = inbox.getMessages();
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception {
for (int i = 0; i < msgs.length; i++) {
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
/* Print the envelope(FromAddress,ReceivedDate,Subject) */
public void printEnvelope(Message message) throws Exception {
Address[] a;
// FROM
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg) {
try {
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
dumpPart(mp.getBodyPart(i));
}
} catch (Exception ex) {
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception {
// Dump input stream ..
if (p.getFileName() == null) {
return;
}
System.out.println("filename:" + p.getFileName());
System.out.println(p.ATTACHMENT);
InputStream is = p.getInputStream();
File file = new File(p.getFileName());
FileOutputStream fout = null;
fout = new FileOutputStream(p.getFileName());
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1) {
fout.write(c);
}
if (fout != null) {
fout.close();
}
}
public static void main(String args[]) {
new MailReader();
}
}