How do I manipulate arrays created from a match.find? - java

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.

Related

How can we open a mail with specific subject and specific date in gmail using Java?

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

Java create DKIM with jDKIM

Can you give me an example for create DKIM with jDKIM?
I don't see any example for this.
http://james.apache.org/jdkim/
Thanks!
Use: james-jdkim
Have a look at this code, This is the answer you are looking for:
lima here is the selector and domain is yahoogroups.com
PublicKeyRecordRetriever publicKeyRecordRetriever = new DNSPublicKeyRecordRetriever();
PublicKeyRecord keys = new DKIMVerifier()
.publicKeySelector(publicKeyRecordRetriever.getRecords("dns/txt", "lima", "yahoogroups.com"));
String signedMIME = "DKIM-Signature: a=rsa-sha256; b=xxxxxxxxxxxxxxxxxx; s=lima; d=yahoogroups.com; v=1; bh=xxxxxxxxx; h=from:to;"
+ "From: test#yahoogroups.com" + "To: test#yahoogroups.com" + "body";
try {
// Verify message against public key
new DKIMVerifier(publicKeyRecordRetriever).verify(new ByteArrayInputStream(signedMIME.getBytes()));
} catch (Exception e) {
throw e;
}
Have a look if this helps. I am also starting with jDKIM. I just wrote a method to list the signature records for the input message. Puzzled how to parse the signature records.
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.james.jdkim.DKIMVerifier;
import org.apache.james.jdkim.api.SignatureRecord;
import org.apache.james.jdkim.exceptions.FailException;
import org.apache.mailet.Mail;
import org.apache.mailet.Mailet;
public class AlgorithmDkimVerification {
public List<SignatureRecord> verifyDkim(InputStream messageStream)
{
DKIMVerifier verifier = new DKIMVerifier();
List<SignatureRecord> records = null;
try {
records = verifier.verify(messageStream);
} catch (IOException | FailException e) {
e.printStackTrace();
}
System.out.println(records);
return records;
}
}

Send email to arraylist retrieved from database

I am working on a project where I am required to retrieve email addresses from database and then send an email to them. I have retrieved those email addresses in arraylist. Like this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javaapplication1.Person;
public class ABC {
public static void main(String[] args) throws SQLException {
ArrayList<Person> personlist = new ArrayList<Person>();
//List<Person> personlist = new List<Person>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","gsjsc","gsjschanna");
Statement st=con.createStatement();
ResultSet srs = st.executeQuery("SELECT * FROM person2");
while (srs.next()) {
Person person = new Person();
person.setName(srs.getString("name"));
person.setJobtitle(srs.getString("jobtitle"));
// person.setFrequentflyer(srs.getInt("frequentflyer"));
personlist.add(person);
}
System.out.println(personlist.size());
for (int a=0;a<personlist.size();a++)
{
System.out.println(personlist.get(a).getName());
System.out.println(personlist.get(a).getJobtitle());
// System.out.println(personlist.get(2).getName());
// System.out.println(personlist.get(3).getName());
}
//System.out.println(personlist.get(4));
//System.out.println(namelist.);
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Person.java: contains all setters and getters.
EDIT
Now I have to send emails to those email addresses retrieved in the arraylist of object person.
I have got a code for sending emails to multiple recipients in arraylist like this:
package javaapplication1;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmailToGroupDemo {
public static void main(String[] args) {
// Create a SendEmail object and call start
// method to send a mail in Java.
SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
sendEmailToGroup.start();
}
private void start() {
// For establishment of email client with
// Google's gmail use below properties.
// For TLS Connection use below properties
// Create a Properties object
Properties props = new Properties();
// these properties are required
// providing smtp auth property to true
props.put("mail.smtp.auth", "true");
// providing tls enability
props.put("mail.smtp.starttls.enable", "true");
// providing the smtp host i.e gmail.com
props.put("mail.smtp.host", "smtp.gmail.com");
// providing smtp port as 587
props.put("mail.smtp.port", "587");
// For SSL Connection use below properties
/*props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");*/
// Create Scanner object to take necessary
// values from the user.
Scanner scanner = new Scanner(System.in);
System.out.println("Please provide your Username for Authentication ...");
final String Username = scanner.next();
System.out.println("Please provide your Password for Authentication ...");
final String Password = scanner.next();
System.out.println("Please provide Email Address from which you want to send Email ...");
final String fromEmailAddress = scanner.next();
System.out.println("Please provide Email Addresses to which you want to send Email ...");
System.out.println("If you are done type : Done or done");
// ArrayLists to store email addresses entered by user
ArrayList< String> emails = (ArrayList< String >) getEmails();
System.out.println("Please provide Subject for your Email ... ");
final String subject = scanner.next();
System.out.println("Please provide Text Message for your Email ... ");
final String textMessage = scanner.next();
// Create a Session object based on the properties and
// Authenticator object
Session session = Session.getDefaultInstance(props,
new LoginAuthenticator(Username,Password));
try {
// Create a Message object using the session created above
Message message = new MimeMessage(session);
// setting email address to Message from where message is being sent
message.setFrom(new InternetAddress(fromEmailAddress));
// setting the email addressess to which user wants to send message
message.setRecipients(Message.RecipientType.BCC, getEmailsList(emails));
// setting the subject for the email
message.setSubject(subject);
// setting the text message which user wants to send to recipients
message.setText(textMessage);
// Using the Transport class send() method to send message
Transport.send(message);
System.out.println("\nYour Message delivered successfully ....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
// This method takes a list of email addresses and
// returns back an array of Address by looping the
// list one by one and storing it into Address[]
private Address[] getEmailsList(ArrayList< String > emails) {
Address[] emaiAddresses = new Address[emails.size()];
for (int i =0;i < emails.size();i++) {
try {
emaiAddresses[i] = new InternetAddress(emails.get(i));
}
catch (AddressException e) {
e.printStackTrace();
}
}
return emaiAddresses;
}
// This method prompts user for email group to which he
// wants to send message
public List< String > getEmails() {
ArrayList< String > emails = new ArrayList< String >();
int counter = 1;
String address = "";
Scanner scanner = new Scanner(System.in);
// looping inifinitely times as long as user enters
// emails one by one
// the while loop breaks when user types done and
// press enter.
while(true) {
System.out.println("Enter E-Mail : " + counter);
address = scanner.next();
if(address.equalsIgnoreCase("Done")){
break;
}
else {
emails.add(address);
counter++;
}
}
return emails;
}
}
// Creating a class for Username and Password authentication
// provided by the user.
class LoginAuthenticator extends Authenticator {
PasswordAuthentication authentication = null;
public LoginAuthenticator(String username, String password) {
authentication = new PasswordAuthentication(username,password);
}
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
This one is a whole different code. But works to send an email to group of people. But problem is we have to enter the email addresses manually. Whereas I want to send the mails to the addresses retrieved from class ABC. Somebody can give me an integrated code (for both the classes) , that would be great.
This should convert a List of Person in an ArrayList of String with the emails from all the persons.
public ArrayList<String> getEmailsFromPersons(List<Person> persons) {
ArrayList<String> emails = new ArrayList<String>();
for(Person person : persons) {
String email = person.getEmail();
if(email != null && !email.trim().isEmpty()) {
emails.add(email);
}
}
return emails;
}
I have retrieved those email addresses in arraylist. Like this:
I do not see any email being set in the Person object. But would still try to answer your question from what I have understood after your edit. Below code should suit your needs (Please don't mind any errors as I am writing it on the fly without any checking):
public class ABC {
public static void main(String[] args) throws SQLException {
ArrayList<Person> personlist = new ArrayList<Person>();
// Creating a separate list of emails for Persons
List<String> personEmails = new ArrayList<String>();
//List<Person> personlist = new List<Person>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","gsjsc","gsjschanna");
Statement st=con.createStatement();
ResultSet srs = st.executeQuery("SELECT * FROM person2");
String email = "";
while (srs.next()) {
Person person = new Person();
person.setName(srs.getString("name"));
person.setJobtitle(srs.getString("jobtitle"));
// person.setFrequentflyer(srs.getInt("frequentflyer"));
// I am assuming you would be setting email in person like this
email = srs.getString("email");
person.setEmail(email);
// Add the email simultaneously to the separate list
personEmails.add(email);
personlist.add(person);
}
System.out.println(personlist.size());
for (int a=0;a<personlist.size();a++)
{
System.out.println(personlist.get(a).getName());
System.out.println(personlist.get(a).getJobtitle());
// System.out.println(personlist.get(2).getName());
// System.out.println(personlist.get(3).getName());
}
//System.out.println(personlist.get(4));
//System.out.println(namelist.);
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
// call the email sender method of yours with the newly created list
SendEmailToGroupDemo sendEmailToGroup = new SendEmailToGroupDemo();
// Obviously, make that start() method public having parameter of type List<String> instead of calling getEmails() within it
sendEmailToGroup.start(personEmails);
// Very little remains to be done, I hope you can figure it out easily
}
}

How to extract a "registration" URL from a mail content

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

How to read MP3 file tags

I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}

Categories