I am successful in reading the content of the gmail-email using "JAVAMail" and I am able to store it in a string. Now I want to get a specific registration URL from the content (String). How can I do this, The String contains plenty of tags and href but I want to extract only the URL that is provided in a hyper link on a word " click here" that exist in the below mentioned statement
"Please <a class="h5" href="https://newstaging.mobilous.com/en/user-register/******" target="_blank">click here</a> to complete your registration".
on the hyper link "click here" the url
href="https://newstaging.mobilous.com/en/user-register/******" target="_blank"
I have tried this by using the following code
package email;
import java.util.ArrayList;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class emailAccess {
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.imap.host",host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.starttls.enable", "true");
properties.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.imap.socketFactory.fallback", "false");
properties.setProperty("mail.imap.socketFactory.port",String.valueOf(993));
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("imap");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
int n=messages.length;
for (int i = 0; i<n; i++) {
Message message = messages[i];
ArrayList<String> links = new ArrayList<String>();
if(message.getSubject().contains("Thank you for signing up for AppExe")){
String desc=message.getContent().toString();
// System.out.println(desc);
Pattern linkPattern = Pattern.compile(" <a\\b[^>]*href=\"[^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(desc);
while(pageMatcher.find()){
links.add(pageMatcher.group());
}
}else{
System.out.println("Email:"+ i + " is not a wanted email");
}
for(String temp:links){
if(temp.contains("user-register")){
System.out.println(temp);
}
}
/*System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());*/
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String host = "imap.gmail.com";
String mailStoreType = "imap";
String username = "rameshakur#gmail.com";
String password = "*****";
check(host, mailStoreType, username, password);
}
}
On executing I got the out put as
< class="h5" href="https://newstaging.mobilous.com/en/user-register/******" target="_blank">
How can I extract only the href value i.e. https://newstaging.mobilous.com/en/user-register/******
Please suggest, thanks.
You're close. You're using group(), but you've got a couple issues. Here's some code that should work, replacing just a bit of what you've got:
Pattern linkPattern = Pattern.compile(" <a\\b[^>]*href=\"([^\"]*)[^>]*>(.*?)</a>", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Matcher pageMatcher = linkPattern.matcher(desc);
while(pageMatcher.find()){
links.add(pageMatcher.group(1));
}
All I did was to change your pattern so it explicitly looks for the end-quote of the href attribute, then wrapped the portion of the pattern that was the string you're looking for in parentheses.
I also added an argument to the pageMather.group() method, as it needs one.
Tell you the truth, you could probably just use this pattern instead (along with the .group(1) change):
Pattern linkPattern = Pattern.compile("href=\"([^\"]*)", Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
Related
I'm trying to automate registration on a website but that site send OTP to the email. so I need to fetch the OTP from the mail and print it to text field.
I am using this code but it's not showing unread message count and the OTP verification mail.
Can anyone help with how can I extract OTP from the email and submit it on the website ?
package MAVEN.GmailIMAP;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class Gmail3 {
public static void ReceiveMail(String FolderName,String SubjectContent, String emailContent, int lengthOfOTP){
String hostName = "imap.gmail.com";//change it according to your mail
String username = "test12345#gmail.com";//username
String password = "test12345"; //password
int messageCount;
int unreadMsgCount;
String emailSubject;
Message emailMessage;
String searchText=null ;
Properties sysProps = System.getProperties();
sysProps.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(sysProps, null);
Store store = session.getStore();
store.connect(hostName, username, password);
Folder emailBox = store.getFolder(FolderName);
emailBox.open(Folder.READ_ONLY);
messageCount = emailBox.getMessageCount();
System.out.println("Total Message Count: " + messageCount);
unreadMsgCount = emailBox.getNewMessageCount();
System.out.println("Unread Emails count:" + unreadMsgCount);
for(int i=messageCount; i>(messageCount-unreadMsgCount); i--)
{
emailMessage = emailBox.getMessage(i);
emailSubject = emailMessage.getSubject();
if(emailSubject.contains(SubjectContent))
{
System.out.println("OTP mail found");
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(emailMessage.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String messageContent=emailContent;
String result = buffer.toString().substring(buffer.toString().indexOf(messageContent));
searchText = result.substring(messageContent.length(), messageContent.length()+lengthOfOTP);
System.out.println("Text found : "+ searchText);
emailMessage.setFlag(Flags.Flag.SEEN, true);
break;
}
emailMessage.setFlag(Flags.Flag.SEEN, true);
}
emailBox.close(true);
store.close();
} catch (Exception mex) {
mex.printStackTrace();
System.out.println("OTP Not found ");
}
return searchText ;
}
public static void main(String[] args) {
ReceiveMail("FolderName","SubjectContent","One Time Password (OTP):",6);
}
}
Below Email body scanner should work for the input which you are looking for
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OtpRegex {
public static void main(String[] args) {
// String regex = "((is|otp|password|key|code|CODE|KEY|OTP|PASSWORD|Do).[0-9]{4,8}.(is|otp|password|key|code|CODE|KEY|OTP|PASSWORD)?)|(^[0-9]{4,8}.(is|otp|password|key|code|CODE|KEY|OTP|PASSWORD))";
String text = "To auth... \n\n869256\n\n Do is your login OTP. Treat this as confidential. Sharing it with anyone gives them full access to your Paytm Wallet. Paytm never calls to verify your OTP.";
Scanner sc = new Scanner(text);
int otp = -1;
String line = null;
while (sc.hasNextLine()) {
line = sc.nextLine().trim();
try{
otp = Integer.parseInt(line);
break;
} catch (NumberFormatException nfx) {
//Ignore the exception
}
}
System.out.println(otp);
}
}
i would like to build a crawler in Java that give me all cookies from a website. This crawler is believed to crawl a list of websites (and obviously the undersides) automatic.
I have used jSoup and Selenium for my plan.
package com.mycompany.app;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class BasicWebCrawler {
private static Set<String> uniqueURL = new HashSet<String>();
private static List<String> link_list = new ArrayList<String>();
private static Set<String> uniqueCookies = new HashSet<String>();
private static void get_links(String url) {
Connection connection = null;
Connection.Response response = null;
String this_link = null;
try {
connection = Jsoup.connect(url);
response = connection.execute();
//cookies_http = response.cookies();
// fetch the document over HTTP
Document doc = response.parse();
// get all links in page
Elements links = doc.select("a[href]");
if(links.isEmpty()) {
return;
}
for (Element link : links) {
this_link = link.attr("href");
boolean add = uniqueURL.add(this_link);
System.out.println("\n" + this_link + "\n" + "title: " + doc.title());
if (add && (this_link.contains(url))) {
System.out.println("\n" + this_link + "\n" + "title: " + doc.title());
link_list.add(this_link);
get_links(this_link);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
get_links("https://de.wikipedia.org/wiki/Wikipedia");
/**
* Hier kommt Selenium ins Spiel
*/
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:\\crawler\\driver\\chromedriver.exe");
driver = new ChromeDriver();
// create file named Cookies to store Login Information
File file = new File("Cookies.data");
FileWriter fileWrite = null;
BufferedWriter Bwrite = null;
try {
// Delete old file if exists
file.delete();
file.createNewFile();
fileWrite = new FileWriter(file);
Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
} catch (Exception ex) {
ex.printStackTrace();
}
for(String link : link_list) {
System.out.println("Open Link: " + link);
driver.get(link);
try {
// loop for getting the cookie information
for (Cookie ck : driver.manage().getCookies()) {
String tmp = (ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure());
if(uniqueCookies.add(tmp)) {
Bwrite.write("Link: " + link + "\n" + (ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure())+ "\n\n");
Bwrite.newLine();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
try {
Bwrite.close();
fileWrite.close();
driver.close();
driver.quit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I test this code on a wikipedia page and compare the result with a cookie scanner call CookieMetrix.
My code shows only four cookies:
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
GeoIP;DE:NW:M__nster:51.95:7.54:v4;.wikipedia.org;/;null;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
WMF-Last-Access-Global;13-May-2019;.wikipedia.org;/;Mon Jan 19 02:28:33 CET 1970;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
WMF-Last-Access;13-May-2019;de.wikipedia.org;/;Mon Jan 19 02:28:33 CET 1970;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
mwPhp7Seed;55e;de.wikipedia.org;/;Mon Jan 19 03:09:08 CET 1970;false
But the cookie scanner shows seven. I don't know why my code shows lesser than the CookieMetrix. Can you help me?
JavaDoc for java.util.Set<Cookie> getCookies():
Get all the cookies for the current domain. This is the equivalent of calling "document.cookie" and parsing the result
document.cookie will not return HttpOnly cookies, simply because JavaScript does not allow it.
Also notice that the “CookieMetrix” seems to list cookies from different domains.
Solutions:
To get a listing such as “CookieMetrix” (1+2) you could add a proxy after your browser and sniff the requests.
In case you want to get all cookies for the current domain, including HttpOnly (1), you could try accessing Chrome’s DevTools API directly (afair, it’ll also return HttpOnly cookies)
I am trying to open a mail in Gmail with a specific subject on a specific date.
I have write down the code where it is fetching all the mails from Gmail in Inbox folder.
How can we get a specific mail content into string format. instead of searching all mails.
how can we search on mails subject name for todays date ?
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class EmailRead {
private static final String MAIL_POP_HOST = "pop.gmail.com";
private static final String MAIL_STORE_TYPE = "pop3";
private static final String POP_USER = "users email";
private static final String POP_PASSWORD = "users password";
private static final String POP_PORT = "995";
public static void getMails(String user, String password) {
user = "slautomation2018#gmail.com";
password = "dontKnow";
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", MAIL_POP_HOST);
properties.put("mail.pop3.port", POP_PORT);
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// Session emailSession = Session.getDefaultInstance(properties);
Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(POP_USER, POP_PASSWORD);
}
});
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore(MAIL_STORE_TYPE);
store.connect(MAIL_POP_HOST, user, password);
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
int m = messages.length-1;
int y = messages.length-2;
System.out.println(messages[m]);
System.out.println(messages[y]);
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println(message.getSubject());
System.out.println(message.getFrom()[0]);
System.out.println(message.getContent().toString());
System.out.println(message.getReceivedDate());
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getMails(POP_USER, POP_PASSWORD);
}
}
Here is the code I have:
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.*;
public class EmailReader {
public static void main(String args[]) {
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", "email#gmail.com", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for (Message message : messages) {
String subject = message.getSubject();
String location = "AAR|RRC|PSD|TPC|HP|SCC|MCA";
List<String> list = new ArrayList<String>();
System.out.println("SUBJECT: " + subject);
System.out.println("DATE: " + message.getSentDate());
Pattern pattern = Pattern.compile(location);
Matcher match = pattern.matcher(subject);
while (match.find()) {
list.add(match.group());
System.out.println(list);
}
}
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
}
I want the program to read each email while searching for the strings saved in locations and store these in an array. This works fine, however I would like each of the abbreviations in the location string be set to an value for determining mileage. I have no idea how I would go about this. In the end I want to be able to sum up all the values from a certain date range of emails based on the numbers found. So, for example, if AAR was set to 15 and showed up in 3 email subject lines and RRC was set to 8 and showed up in 2, it would sum it all up and print it out.
Ended up using:
if(match.group().contains("AAR"){
Then do this string of code
}
It looks pretty sloppy since I have a bunch of if statements but works. Might be better to use a switch instead.
Hi there I am trying to
Download attachments in e-mail messages using JavaMail
Reference from this site: Download attachments in e-mail messages using JavaMail
However, I am getting the following error:
Could not connect to the message store javax.mail.AuthenticationFailedException: [AUTH] Username and password not accepted.
Below is the code:
public class EmailAttachmentReceiver {
private String saveDirectory;
/**
* Sets the directory where attached files will be stored.
* #param dir absolute path of the directory
*/
public void setSaveDirectory(String dir) {
this.saveDirectory = dir;
}
/**
* Downloads new messages and saves attachments to disk if any.
* #param host
* #param port
* #param userName
* #param password
*/
public void downloadEmailAttachments(String host, String port,
String userName, String password) {
Properties properties = new Properties();
// server setting
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", port);
// SSL setting
properties.setProperty("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port",
String.valueOf(port));
Session session = Session.getDefaultInstance(properties);
try {
// connects to the message store
Store store = session.getStore("pop3");
store.connect(userName, password);
// opens the inbox folder
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
// fetches new messages from server
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
// store attachment file name, separated by comma
String attachFiles = "";
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();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
// print out details of each message
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + attachFiles);
}
// disconnect
folderInbox.close(false);
store.close();
} catch (NoSuchProviderException ex) {
System.out.println("No provider for pop3.");
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Runs this program with Gmail POP3 server
*/
public static void main(String[] args) {
String host = "pop.gmail.com";
String port = "995";
String userName = "your_email";
String password = "your_password";
String saveDirectory = "E:/Attachment";
EmailAttachmentReceiver receiver = new EmailAttachmentReceiver();
receiver.setSaveDirectory(saveDirectory);
receiver.downloadEmailAttachments(host, port, userName, password);
}
}
First, correct these common mistakes.
Clearly the server thinks you've supplied the wrong username and password. If you turn on session debugging, you may find more clues as to what the server thinks is wrong. You may also need to set the "mail.debug.auth" property to "true" to see the full authentication protocol exchange.
import com.packaging.dbconnection.Database;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
/**
* This program demonstrates how to download e-mail messages and save
* attachments into files on disk.
*
* #author www.codejava.net
*
*/
public class EmailAttachmentReceiver {
private String saveDirectory;
/*vxcvxcv*/
/**
* Sets the directory where attached files will be stored.
* #param dir absolute path of the directory
*/
public void setSaveDirectory(String dir) {
this.saveDirectory = dir;
}
/**
* Downloads new messages and saves attachments to disk if any.
* #param host
* #param port
* #param userName
* #param password
*/
public void downloadEmailAttachments(String host, String port,
String userName, String password) {
PreparedStatement pst;
ResultSet rs;
Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "imaps");
//session reading
// server setting
// properties.put("mail.pop3.host", host);
// properties.put("mail.pop3.port", port);
// SSL setting
// properties.setProperty("mail.pop3.socketFactory.class",
// "javax.net.ssl.SSLSocketFactory");
// properties.setProperty("mail.pop3.socketFactory.fallback", "false");
// properties.setProperty("mail.pop3.socketFactory.port",
// String.valueOf(port));
try {
// connects to the message store
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore();
//store.connect(userName, password);
store.connect("imap.gmail.com", "yourmail#gmail.com", "yourpass");
//Folder inbox = store.getFolder("INBOX");
// inbox.open(Folder.READ_ONLY);
// opens the inbox folder
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
// fetches new messages from server
SearchTerm sender = new FromTerm(new InternetAddress("xyz#gmail.com"));
// Message[] messages = inbox.search(sender);
Message[] arrayMessages = folderInbox.search(sender);
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
// store attachment file name, separated by comma
String attachFiles = "";
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();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
// print out details of each message
System.out.println("Message " + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t Subject: " + subject);
System.out.println("\t Recieved Date: " + sentDate);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + attachFiles);
try{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String user="root";
String pass="";
Class.forName(driver);
Connection con=DriverManager.getConnection(url,user,pass);
pst=con.prepareStatement("insert into applications() VALUES (?,?,?,?,?)");
pst.setString(1,i+"1");
pst.setString(2,from);
pst.setString(3,subject);
pst.setString(4,sentDate);
pst.setString(5,attachFiles);
int j = pst.executeUpdate();
if(con!=null){
System.out.println("connected");
}
}
catch (ClassNotFoundException ex) {
Logger.getLogger(EmailAttachmentReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
catch (SQLException ex) {
Logger.getLogger(EmailAttachmentReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
}
// disconnect
folderInbox.close(false);
store.close();
} catch (NoSuchProviderException ex) {
System.out.println("No provider for pop3.");
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Runs this program with Gmail POP3 server
*/
public static void main(String[] args) {
String host = "pop.gmail.com";
String port = "995";
String userName = "yourmail#gmail.com";
String password = "yourpass";
String saveDirectory = "D:/Attachment";
EmailAttachmentReceiver receiver = new EmailAttachmentReceiver();
receiver.setSaveDirectory(saveDirectory);
receiver.downloadEmailAttachments(host, port, userName, password);
}
}
In above code I have given downloading attachment code and with this I have also saved that emails in database in D:/Attachment folder.So hope you will find what you want.