trying to search a mail with subject in Gmail using java - java

My company mail domain is Gmail , and I need to search a mail using subject line. I have written below code but Gmail is not connecting with correct user id and password.
public static void getMail() {
Scanner sc = new Scanner(System.in);
final String m10 = "abc#abc.com";
final String n10 = "abcd";
String host = "absmtp.abc.com";
try
{
Properties pro1 = new Properties();
pro1.put("mail.smtp.host", host);
pro1.put("mail.smtp.socketFactory.port", "465");
MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
pro1.put("mail.imaps.ssl.socketFactory", socketFactory);
// pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// pro1.put("mail.smtp.auth", "true");
pro1.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(pro1);
Store store = session.getStore("imaps");
store.connect(host, m10, n10);
Folder folderbox = store.getFolder("INBOX");
folderbox.open(Folder.READ_ONLY);
SearchTerm search = new SearchTerm(){
#Override
public boolean match(Message message) {
try
{
if(message.getSubject().contains("") )
{
return true;
}
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
return false;
}
};
Message[] found = folderbox.search(search);
int length = found.length;
for(int i = 0;i<found.length;i++)
{
Message mess1 = found[i];
System.out.println("->Message Number > "+i);
System.out.println("->Message Subject >"+mess1.getSubject());
}
folderbox.close(true);
store.close();
}
catch(Exception e)
{
System.err.println(e.getMessage());
}
}
is not connecting and giving error :
Couldn't connect to host, port: abc#abc.com, 993; timeout -1.

Related

How to get Bounced mails in java

I am implementing a Bulk mail application, in this applica This link.
I am able to connect to the server and and send the emails to the destination addresses, but I want to identify the undelivered mails.
By using below program I am able to get the email subjects. But based on the subject it will be difficult to identify the exact undelivered mails.
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.host", host);
props.setProperty("mail.user", user);
props.setProperty("mail.from", from);
//props.setProperty("mail.debug", "true");
//props.setProperty("mail.domain", domain);
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore(protocol);
Session session1 = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
System.out.println((store.isConnected())?"Already Connected":"Not Already Connected");
store.connect(host, port, user, password);
Folder inbox = store.getFolder("INBOX");
System.out.println("folder>>>" + inbox.getFullName() + "<<<");
System.out.println("folder URLName>>>" + inbox.getURLName() + "<<<");
System.out.println((inbox.exists()?"folder exists":"folder does not exist"));
int folderType = inbox.getType();
System.out.println("folder type>>>" + folderType + "<<<");
inbox.open(Folder.READ_WRITE);
System.out.println("Message Count:" + inbox.getMessageCount());
Message[] m = inbox.getMessages();
for (int x = 0; x < m.length; x++) {
System.out.println(m[x].getSubject());
}
inbox.close(false);
store.close();
}catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
How can I get the undelivered mails(Bounced).
I am using Hmailserver as my mail server.
You can use this below code
MimeMessage payload = (MimeMessage) message.getPayload();
Multipart mp = (Multipart) payload.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart bodyPart = mp.getBodyPart(i);
StringWriter writer = new StringWriter();
IOUtils.copy(bodyPart.getInputStream(), writer);
System.out.println("Content inputstream: " + writer.toString());
}

Reading Error in Mail JAVA

I am reading email from gmail.com. i have read some of the mail successfully but after a while i got this,
java.lang.ClassCastException:
javax.mail.internet.MimeMultipart cannot be cast to java.lang.String
at emailIngestion.EmailIngestion.check(EmailIngestion.java:66)
at emailIngestion.EmailIngestion.main(EmailIngestion.java:106).
Actually my requirement is to store content into a variable and then store it in arraylist and then again write it to a file... i have implemented it using this code so if any better ideas are there please share me.
public class EmailIngestion {
static ArrayList<EmailModel> contentList=new ArrayList<EmailModel>();
static ArrayList<EmailModel> metaDataList= new ArrayList<EmailModel>();
public static void check(String host, String storeType, String user,
String password) throws IOException
{
FileWriter fw= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_metadata.csv",true);
FileWriter fw1= new FileWriter("C:\\Users\\Admin\\Desktop\\murtaza_content.txt",true);
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
int emailNumber;
String mailContent = null,from = null,to = null,mailContentType = null,subject = null;
Date recievedDate= new Date();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Subject is"+message.getSubject());
subject = message.getSubject();
from = message.getFrom()[0].toString();
mailContentType=message.getContentType();
recievedDate=message.getSentDate();
to=InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
emailNumber=message.getMessageNumber();
metaDataList.add(new EmailModel(from, to, subject, mailContentType, recievedDate,emailNumber));
fw.write(emailNumber+"\001"+from+"\001"+subject+"\001"+recievedDate+mailContentType+"\001"+" \n");
fw.flush();
if(message.isMimeType("multipart/*")){
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
mailContent=(String) bodyPart.getContent();
System.out.println(mailContent);
}
}
else{
mailContent=(String) message.getContent();
System.out.println(message.getContent());
}
contentList.add(new EmailModel(mailContent, emailNumber));
fw1.write(emailNumber+","+mailContent+"\n");
}
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) throws IOException {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "abcd#gmail.com";// change accordingly
String password = "******";// change accordingly
check(host, mailStoreType, username, password);
}
}
Thanks in advance
If the services are fluctuating then its definitely not stable. Which version of 1.3 you are using? As you are using one node make sure that you have master and worker services are installed and running. This you can see from your cluster manager. The info from logs is not informative enough to nail down the issue.

JavaMail API Error (javax.mail.NoSuchProviderException: invalid provider)

I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Exception is coming when try to send emal using jsp servlet :javax.mail.internet.AddressException

I try to send emails using jsp. All the things working perfect but when I try to use more than one email addresses it shows error ,
javax.mail.internet.AddressException: Illegal address in string ``
here is my code
public EmailSender(String[] to, String subject, String msg) {
final String txtFromAcc = "abeywicrema#gmail.com";
final String pwfFromPW = "mjkkmqzrkkgsydqk";
String txtFrom = "norply#politeknick.com";
//String txtTo = "abeywicrema#gmail.comshan.a#jinasena.com.lk";//to;
String txtSubject = subject;
String txaMessage = msg;
String[] sendMore = to;//{"abeywicrema#gmail.com", "shan.a#jinasena.com.lk"};
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.debug", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(txtFromAcc, pwfFromPW);
}
};
Session session = Session.getDefaultInstance(prop, auth);
try {
Message mail = new MimeMessage(session);
mail.setFrom(new InternetAddress(txtFrom));
InternetAddress[] addressTo = new InternetAddress[sendMore.length];
for (int i = 0; i < sendMore.length; i++) {
addressTo[i] = new InternetAddress(sendMore[i]);
}
mail.setRecipients(Message.RecipientType.TO, addressTo);
mail.setSubject(txtSubject);
mail.setContent(txaMessage, "text/plain");
Transport.send(mail);
//OptionPane.showMessageDialog(this, "Sent");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>msg has been sent ");
}

Validate smtp server credentials using java without actually sending mail

To verify smtp server credentials shall I use transport.connect()?
Session session = Session.getInstance(properties,authenticator);
Transport tr=session.getTransport("smtp");
tr.connect();
Is it correct method to check smtp server credentials?
This question: 'Verify mail server connection programmatically in ColdFusion' has a java solution as part of the accepted answer:
int port = 587;
String host = "smtp.gmail.com";
String user = "username#gmail.com";
String pwd = "email password";
try {
Properties props = new Properties();
// required for gmail
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
// or use getDefaultInstance instance if desired...
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect(host, port, user, pwd);
transport.close();
System.out.println("success");
}
catch(AuthenticationFailedException e) {
System.out.println("AuthenticationFailedException - for authentication failures");
e.printStackTrace();
}
catch(MessagingException e) {
System.out.println("for other failures");
e.printStackTrace();
}
public boolean confirmSMTP(String host, String port, String username, String password, String auth, String enctype) {
boolean result = false;
try {
Properties props = new Properties();
if (auth.equals(true)) {
props.setProperty("mail.smtp.auth", "true");
} else {
props.setProperty("mail.smtp.auth", "false");
}
if (enctype.endsWith("TLS")) {
props.setProperty("mail.smtp.starttls.enable", "true");
} else if (enctype.endsWith("SSL")) {
props.setProperty("mail.smtp.startssl.enable", "true");
}
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
int portint = Integer.parseInt(port);
transport.connect(host, portint, username, password);
transport.close();
result = true;
} catch(AuthenticationFailedException e) {
Logging.addMsg(e.toString(), "SMTP: Authentication Failed", false, true);
} catch(MessagingException e) {
Logging.addMsg(e.toString(), "SMTP: Messaging Exception Occurred", false, true);
} catch (Exception e) {
Logging.addMsg(e.toString(), "SMTP: Unknown Exception", false, true);
}
return result;
}

Categories