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/
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'm working on project in spring boot, where I need read details of the mails.
First I'm storing unread mails into message[] array and I'm reading first 50 mails and again next 50 mails and so on.
But when I do so some of the mails are missing out i.e., in 50 mails some number of mails are not read and details are not recorded.
Below is the function where I am doing all this operations.
Please help me to improve my code.
public List<Object> read(){
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
String userName=resourceBundle.getString("mailUserName");
String password=resourceBundle.getString("mailPassword");
Session session = Session.getInstance(properties,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
Store store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
SearchTerm recentTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
SearchTerm fromTerm = new FromTerm(new InternetAddress(resourceBundle.getString("receiveMailFrom")));
SearchTerm unreadTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
SearchTerm subjectTerm = new SubjectTerm(this.subjectTerm);
SearchTerm subjectAndUnreadTerm = new AndTerm(subjectTerm, unreadTerm);
SearchTerm recentAndFromTerm = new AndTerm(recentTerm, fromTerm);
SearchTerm subjectAndUnreadAndFromTerm = new AndTerm(subjectAndUnreadTerm, fromTerm);
Message messages[] = inbox.search(subjectAndUnreadAndFromTerm);
List<Object> readParams=new ArrayList<>();
if (messages.length<count)
logger.info("Number of mails = " + messages.length);
else
logger.info("Number of mails = " + count);
for (Message message : messages) {
if(mailcount<count) {
Address[] from = message.getFrom();
logger.info("-------------------------------");
logger.info("Date : " + message.getSentDate());
logger.info("From : " + from[0]);
logger.info("Subject: " + message.getSubject());
logger.info("Content :");
fileNames = processMessageBody(message);
logger.info("--------------------------------");
mailcount +=1;
}
else{
break;
}
}
inbox.close(true);
store.close();
if(messages.length==0)
{
readParams.add(0);
return readParams;
}
else {
readParams.add(1);
readParams.add(fileNames);
return readParams;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I have an EML file which contains another EML file as an attachment.
When I try to fetch an attachment file using JAVAMAIL API, getDisposition value indicates attachment but getfileName() displays NULL.
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream("C:\\Mail1496085.eml");
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
System.out.println("Parts:::"+numberOfParts);
String wi="IM-67890-PROCESS";
String saveDir = System.getProperty("user.dir")+"\\Docs";
saveDir=saveDir + File.separator+wi;
boolean file =new File(saveDir).mkdir();
if (file) {
System.out.println("Directory: " + wi + " created");
// logger.debug("Directory: " + workItem + " created");
}
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
String disposition=part.getDisposition();
if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
// this part is attachment
String fileName = part.getFileName();
String extension="";
System.out.println("Attached File Name::"+fileName);
saveDir=saveDir + File.separator + fileName;
int i=fileName.lastIndexOf(".");
if(i>0)
{
extension=fileName.substring(i+1);
}
if(extension.equalsIgnoreCase("eml"))
{
part.saveFile(saveDir);
extractEML(saveDir, wi);
System.out.println("This is a eml file");
}
else if(extension.equalsIgnoreCase("msg"))
{
part.saveFile(saveDir);
extractMSG(saveDir,wi);
System.out.println("This is a msg file");
}
else
{
System.out.println("This is other file");
}
} else {
System.out.println("Not an eml file");
System.out.println("File Name::"+part.getFileName());
}
}
}
}
public static void extractEML(String emlPath,String wi) throws MessagingException, IOException
{
//String fileName="";
String path=System.getProperty("user.dir") + File.separator + "Docs" + File.separator + wi + File.separator + "EML_PDF";
boolean file =new File(path).mkdir();
if(file)
{
System.out.println("Folder EML_PDF Created Successfully");
}
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream(emlPath);
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
System.out.println("Parts:::"+numberOfParts);
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String fileName = part.getFileName();
String extension="";
path=path + File.separator + fileName;
int i=fileName.lastIndexOf(".");
if(i>0)
{
extension=fileName.substring(i+1);
}
if(extension.equalsIgnoreCase("pdf"))
{
part.saveFile(path);
}
}
}
}
}
File names for attachments are optional. You need to fix your program to work without a file name.
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream inputStream = new FileInputStream(FilePath);
MimeMessage message = new MimeMessage(mailSession, inputStream);
MimeMessageParser mimeParser = new MimeMessageParser(message);
mimeParser.parse();
List<DataSource> dsl = mimeParser.getAttachmentList();
for(DataSource ds : dsl) {
InputStream file = ds.getInputStream();
}
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 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();
}
}