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);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have write a readFromSharedInbox() method. When I am checking the code with sonarLint i am getting this error "Refractor this method to reduce its cognitive complexity". So i want to break this method in two parts. But i am not able to do so.I am trying to create a method to read the mail from inbox.
My Code look like this
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.ReceivedDateTerm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
#Service
public class MailServiceImpl implements MailService {
#Value("${mail.host}")
private String host;
#Value("${mail.id}")
private String mailBoxId;
#Value("${mail.password}")
private String password;
#Value("${mail.protocol}")
private String protocol;
#Value("${mail.socketfactory}")
private String socketfactory;
#Value("${mail.fallback}")
private String fallback;
#Value("${mail.port}")
private String port;
#Value("${mail.savepath}")
private String savepath;
#Value("${submission.fields}")
private String fields;
#Value("${mail.endidentifier}")
private String mailEndIdentifier;
#Autowired
private EmailRequestRepository emailRequestRepository;
#Autowired
private CoreWorkflowService coreWorkflowService;
public void readFromSharedInbox() {
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail.imaps.socketFactory.class", socketfactory);
props.setProperty("mail.imaps.socketFactory.fallback", fallback);
props.setProperty("mail.imaps.port", port);
props.setProperty("mail.imaps.socketFactory.port", port);
Session session = Session.getDefaultInstance(props, null);
try {
Store store = session.getStore(protocol);
store.connect(host, mailBoxId, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
ReceivedDateTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date());
FlagTerm seenTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] todaysMessages = inbox.search(receivedDateTerm);
Message[] foundMessages = inbox.search(seenTerm, todaysMessages);
List<EmailRequest> emailRequestList = new ArrayList<>();
for (int i = 0; i < foundMessages.length; i++) {
Message message = foundMessages[i];
String subject = message.getSubject();
String content = message.getContent().toString();
String contentType = message.getContentType();
Address[] froms = message.getFrom();
String sender = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
Date recieveDate = message.getReceivedDate();
// store attachment file name, separated by comma
StringBuilder attachFiles=new StringBuilder();
if (contentType.contains("multipart")) {
// content may contain attachments
MimeMultipart multiPart = (MimeMultipart) message.getContent();
content = getTextFromMimeMultipart(multiPart);
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();
if (attachFiles.length() > 0) {
attachFiles.append(",");
attachFiles.append(fileName);
} else {
attachFiles.append(fileName);
}
System.out.println(fileName);
}
}
message.writeTo(new FileOutputStream(new File(savepath + sanitizeFileName(subject) + ".eml")));
}
System.out.println("Content type: " + contentType);
EmailRequest emailRequest = EmailRequest.builder().emailRecieveDate(recieveDate).subjectEmail(subject)
.emailContent(content).fromEmail(sender).toEmail(mailBoxId).isMailProcessed(false).build();
emailRequestList.add(emailRequest);
}
inbox.close(false);
store.close();
System.out.println("reading done!");
emailRequestRepository.saveAll(emailRequestList);
System.out.println("Email data saved successfully in db table");
} catch (Exception e) {
e.printStackTrace();
}
}
private String sanitizeFileName(String subject) {
return subject.replaceAll("[:\\\\/*?|<>]", "_");
}
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws IOException, MessagingException {
int count = mimeMultipart.getCount();
if (count == 0)
throw new MessagingException("Multipart with no body parts not supported.");
boolean multipartAlt = new ContentType(mimeMultipart.getContentType()).match("multipart/alternative");
if (multipartAlt)
// alternatives appear in an order of increasing
// faithfulness to the original content. Customize as req'd.
return getTextFromBodyPart(mimeMultipart.getBodyPart(count - 1));
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
result.append(getTextFromBodyPart(bodyPart));
}
return result.toString();
}
private String getTextFromBodyPart(BodyPart bodyPart) throws IOException, MessagingException {
String result = "";
if (bodyPart.isMimeType("text/plain")) {
result = (String) bodyPart.getContent();
} else if (bodyPart.isMimeType("text/html")) {
result = (String) bodyPart.getContent();
} else if (bodyPart.getContent() instanceof MimeMultipart) {
result = getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
}
return result;
}
#Override
public void readMailDetailsFromDb() {
EmailRequest email = new EmailRequest();
email.setIsMailProcessed(false);
Example<EmailRequest> whereClause = Example.of(email);
List<EmailRequest> findAll = emailRequestRepository.findAll(whereClause);
Map<String, Object> processVariables = null;
for (EmailRequest emaeil : findAll) {
System.out.println(emaeil.getSubjectEmail() + " : " + emaeil.getEmailId());
processVariables = EmailParserUtil.parse(fields, emaeil.getEmailContent(), mailEndIdentifier);
// workflow service
try {
Workflow startWorkflow = coreWorkflowService.startWorkflow(Constants.SUBMISSION_PROCESS_ID, Constants.MAIL, processVariables);
startWorkflow.toString();
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
// update mail
emaeil.setMailProcessedOn(LocalDateTime.now() ) ;
emaeil.setIsMailProcessed(true) ;
emailRequestRepository.save(emaeil) ;
}
}
}
This is MailService Class
import java.lang.reflect.InvocationTargetException;
public interface MailService {
public void readFromSharedInbox();
public void readMailDetailsFromDb() throws IllegalAccessException, InvocationTargetException;
}
You can use your IDE for things like that.
You select a part of your code, right click on it and refactor it by extracting the code in a new private method.
For exemple, you can do this on the "for" statement.
Or the "if (contentType.contains("multipart"))" part with a manageMultipart method.
Keep getting this error
"java.util.NoSuchElementException: No line found error java"
and searched through code so many times and cant see to find problems heres my files can anyone help?
Am currently doing this as an assignment and am trying to transfer it from unthreaded to threaded and in the process came up with this error!!
This is the Client class
package Client;
import core.Email;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
public class EmailClient {
public static void main(String[] args) {
try
{
// Step 1 (on consumer side) - Establish channel of communication
Socket dataSocket = new Socket("localhost", EmailServiceDetails.LISTENING_PORT);
// Step 3) Build output and input objects
OutputStream out = dataSocket.getOutputStream();
PrintWriter output = new PrintWriter(new OutputStreamWriter(out));
InputStream in = dataSocket.getInputStream();
Scanner input = new Scanner(new InputStreamReader(in));
Scanner keyboard = new Scanner(System.in);
String message = "";
while(!message.equals(EmailServiceDetails.END_SESSION))
{
displayMenu();
int choice = getNumber(keyboard);
String response = "";
if(choice >=0 && choice < 3)
{
switch (choice)
{
case 0:
message = EmailServiceDetails.END_SESSION;
// Send message
output.println(message);
output.flush();
response = input.nextLine();
if(response.equals(EmailServiceDetails.SESSION_TERMINATED))
{
System.out.println("Session ended.");
}
break;
case 1:
message = sendEmail(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.SUCCESSFUL_ADD))
{
System.out.println("Email sent successfully");
}
else if(response.equals(EmailServiceDetails.UNSUCCESSFUL_ADD))
{
System.out.println("Sorry, the email could not be sent at this time.");
}
break;
case 2:
message = viewUnread(keyboard);
// Send message
output.println(message);
output.flush();
// Get response
response = input.nextLine();
if(response.equals(EmailServiceDetails.NO_UNREAD))
{
System.out.println("No unread mails found for that account.");
}
else
{
ArrayList<Email> unreadMails = EmailServiceDetails.parseEmailList(response);
System.out.println("Unread Emails:");
for(Email e: unreadMails)
{
System.out.println(e);
}
}
break;
}
if(response.equals(EmailServiceDetails.UNRECOGNISED))
{
System.out.println("Sorry, that request cannot be recognised.");
}
}
else
{
System.out.println("Please select an option from the menu");
}
}
System.out.println("Thank you for using the Email system.");
dataSocket.close();
}catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
public static void displayMenu()
{
System.out.println("0) Exit");
System.out.println("1) Send an email");
System.out.println("2) View all unread mails");
}
public static int getNumber(Scanner keyboard)
{
boolean numberEntered = false;
int number = 0;
while(!numberEntered)
{
try{
number = keyboard.nextInt();
numberEntered = true;
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number.");
keyboard.nextLine();
}
}
keyboard.nextLine();
return number;
}
public static String sendEmail(Scanner keyboard)
{
System.out.println("Please enter the sender of this email:");
String sender = keyboard.nextLine();
// Get recipient information
String anotherRecipient = "Y";
ArrayList<String> recipients = new ArrayList();
while(anotherRecipient.equalsIgnoreCase("Y"))
{
System.out.println("Enter the recipient's email address:");
String recipient = keyboard.nextLine();
recipients.add(recipient);
System.out.println("Would you like to add another recipient? ('Y' for yes and 'N' for no)");
anotherRecipient = keyboard.nextLine();
}
System.out.println("Please enter the email subject:");
String subject = keyboard.nextLine();
System.out.println("Please enter the message body:");
String body = keyboard.nextLine();
// Get attachment information
ArrayList<String> attachments = new ArrayList();
System.out.println("Would you like to enter an attachment ('Y' to add and 'N' to continue)");
String anotherAttachment = keyboard.nextLine();
while(anotherAttachment.equalsIgnoreCase("Y"))
{
System.out.println("Enter the attachment information:");
String attachment = keyboard.nextLine();
attachments.add(attachment);
System.out.println("Would you like to add another attachment? ('Y' for yes and 'N' to Continue)");
anotherAttachment = keyboard.nextLine();
}
long timestamp = new Date().getTime();
String response = null;
Email e = null;
if(attachments.size() > 0)
{
e = new Email(sender, recipients, subject, body, timestamp, attachments);
}
else
{
e = new Email(sender, recipients, subject, body, timestamp);
}
response = EmailServiceDetails.ADD_MAIL + EmailServiceDetails.COMMAND_SEPARATOR + EmailServiceDetails.formatEmail(e);
return response;
}
public static String viewUnread(Scanner keyboard)
{
System.out.println("Please enter the name of the email account you wish to see unread mail for:");
String recipient = keyboard.nextLine();
String response = EmailServiceDetails.VIEW_UNREAD + EmailServiceDetails.COMMAND_SEPARATOR + recipient;
return response;
}
}
--------------------------------------------------------------------------------
This is Server
---------------
package Server;
import Server.Commands.Command;
import core.EmailServiceDetails;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class EmailServer {
public static void main(String[] args) {
try{
// Set up a connection socket for other programs to connect to
ServerSocket listeningSocket = new ServerSocket(EmailServiceDetails.LISTENING_PORT);
// Create the list of emails to be stored and worked with
EmailStore emails = new EmailStore();
boolean continueRunning = true;
int threadCount = 0;
while(continueRunning)
{
// Step 2) wait for incoming connection and build communications link
Socket dataSocket = listeningSocket.accept();
threadCount++;
System.out.println("The server has now accepted " + threadCount + " clients");
// Step 3) Build thread
// Thread should be given:
// 1) a group to be stored in
// 2) a name to be listed under
// 3) a socket to communicate through
// 4) Any extra information that should be shared
EmailThread newClient = new EmailThread (emails, dataSocket.getInetAddress()+"", dataSocket,threadCount);
newClient.start();
}
listeningSocket.close();
}
catch(Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
--------------------------------------------------------------------------------
This is ServerThread
---------------
package Server;
import Server.Commands.Command;
import Server.EmailStore;
import core.EmailServiceDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
/**
*
* #author User
*/
public class EmailThread extends Thread {
private Socket dataSocket;
private Scanner input;
private PrintWriter output;
private int number;
private EmailStore emails;
public EmailThread(EmailStore emails,String name, Socket dataSocket, int number) {
try {
// Save the data socket used for communication between the thread and the Client
this.dataSocket = dataSocket;
// Save the id of the thread to identify output
// Save the id of the thread to identify output
this.number = number;
input = new Scanner(new InputStreamReader(this.dataSocket.getInputStream()));
// Create the stream for writing to the Client
output = new PrintWriter(this.dataSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("An exception occurred while setting up connection links for a thread: " + e.getMessage());
}
}
#Override
public void run() {
{
String incomingMessage = "";
String response;
try {
while (!incomingMessage.equals(EmailServiceDetails.END_SESSION)) {
// Wipe the response to make sure we never use an old value
response = null;
// take in information from the client
incomingMessage = input.nextLine();
System.out.println("Received message: " + incomingMessage);
// Break up information into components
String[] components = incomingMessage.split(EmailServiceDetails.COMMAND_SEPARATOR);
// Confirm that the command was correctly formatted
// Did it include more than just the command text?
if (components.length > 1) {
CommandFactory factory = new CommandFactory();
// Figure out which command was sent by the client
// I.e. what does the client want to do?
Command command = factory.createCommand(components[0]);
// Take the remaining text the client sent (i.e. all the information provided)
// and execute the requested action (e.g. store the new mail, get all sent mails etc)
response = command.createResponse(components[1], emails);
} else if (components[0].equals(EmailServiceDetails.END_SESSION)) {
response = EmailServiceDetails.SESSION_TERMINATED;
} else {
// If information was missing, set the response to inform the
// client that the command wasn't recognised
response = EmailServiceDetails.UNRECOGNISED;
}
// Send back the computed response
output.println(response);
output.flush();
}
} catch (Exception e) {
System.out.println("An exception occurred while communicating with client #" + number + ": " + e.getMessage());
} finally {
try {
// Shut down connection
System.out.println("\n* Closing connection with client #" + number + "... *");
dataSocket.close();
} catch (IOException e) {
System.out.println("Unable to disconnect: " + e.getMessage());
System.exit(1);
}
}
}
}
}
--------------------------------------------------------------------------------
This is EmailStore
---------------
package Server;
import core.Email;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class EmailStore
{
private ArrayList<Email> emailList = new ArrayList();
public boolean addMail(Email newEmail)
{
return emailList.add(newEmail);
}
public boolean removeMail(Email mailToBeDeleted)
{
return emailList.remove(mailToBeDeleted);
}
public ArrayList<Email> findEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient
.filter(email -> email.getRecipients().contains(recipient))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
public ArrayList<Email> findEmailBySender(String sender)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails matching the specified sender
.filter(email -> email.getSender().equals(sender))
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
// Methods to mark emails as read
// Provide a version that marks multiple mails as read AND a version that
// marks a single email as read
public void markMultipleAsRead(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsRead(e);
}
}
public void markAsRead(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsRead(true);
}
}
// Methods to mark emails as spam
// Provide a version that marks multiple mails as spam AND a version that
// marks a single email as spam
public void markAsSpam(Email e)
{
int index = emailList.indexOf(e);
if(index != -1)
{
Email storedMail = emailList.get(index);
storedMail.markAsSpam(true);
}
}
public void markMultipleAsSpam(ArrayList<Email> emails)
{
for(Email e : emails)
{
markAsSpam(e);
}
}
public ArrayList<Email> findUnreadEmailByRecipient(String recipient)
{
ArrayList<Email> results = new ArrayList();
results = (ArrayList<Email>) emailList.stream()
// Find all emails whose recipients list contents the specified recipient AND the email is not unread
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
// Collect the results back into a List (this does not return an ArrayList, so need to cast)
.collect(Collectors.toList());
return results;
}
}
-------
Help Appreciated
-
----------
Help would be great appreciated as the frustration levels are at a high!!
This answer is a wild guess but in case 1 of the switch statement of the main method you are calling the input.nextLine() scanner which it might not contain information at that time. It is possible that you have to check if data arrived by using the hasNext() method first.
Also in the last method when you are collecting the email classes you don't really need to cast. It can be done like this:
results = emailList.stream()
.filter(email -> email.getRecipients().contains(recipient) && !email.isRead())
.collect(Collectors.toCollection(ArrayList::new));
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);
}
}
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);
ok so I use .getcontent and receive javax.mail.internet.MimeMultipart#fd13b5 etc.
I know i need something like this in my code but i dont know what exactly is needed.
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure && !saveAttachments)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
at the moment i am trying to put all the information in to astring which is then shown up on a GUI at the moment i have it all working fine bar the body content which is showing as.
javax.mail.internet.MimeMultipart#fd13b5. any help would be much appreciated as im quite stuck.
package EmailTable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email implements ActionListener
{
private mail mail;
private List mails;
private String password;
private String user;
private String getText;
private boolean textIsHtml = false;
public Email(List mails,String password,String user) throws MessagingException, IOException {
password = "password";
user = "user";
this.mails = mails;
String host = "10..10.10.10";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
int length = messages.length-1;
for (int i = length; i > length-30; i--) {
mail = new mail();
mail.setEmail(messages[i].getFrom()[0]);
String to = InternetAddress.toString(
messages[i].getRecipients(Message.RecipientType.TO));
if (to != null) {
mail.setEmail2(to);
}
mail.setSubject(messages[i].getSubject());
mail.setDate(messages[i].getSentDate());
mail.setMessage(messages[i]);
mail.setContent(((MimeMessage)messages[i]).getContent());
Email.this.mails.add(mail);
}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Yes, you have to iterate through each BodyPart to know it's type and then get the content accordingly. Here's what I used to get the content of a message. But still I am not able to get the right content for some messages.
Edited
Works better after implementing the code suggested by Bill.
Object msgContent = messages[i].getContent();
String content = "";
/* Check if content is pure text/html or in parts */
if (msgContent instanceof Multipart) {
Multipart multipart = (Multipart) msgContent;
Log.e("BodyPart", "MultiPartCount: "+multipart.getCount());
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) {
System.out.println("Mail have some attachment");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
}
else {
content = getText(bodyPart); // the changed code
}
}
}
else
content= messages[i].getContent().toString();
This solution worked much better for me. I merely wanted to log my email message for development/testing purposes. Use the MimeMessage.writeTo(OutputStream) method.
void logMimeMessage(MimeMessage msg) throws MessagingException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
msg.writeTo(out);
} catch (IOException e) {
logger.catching(new MyException("Cannot log MimeMessage",e));
}
logger.error(out.toString());
}
Thanks to the comment by #zzzzz above, who linked to this answer JavaMail - Parsing email content, can't seem to get it to work! (Message.getContent())