Java sending a mail via tomcat server - java

I'm trying to send a mail via android application, the mail has to be sent through my server (because the mail API of Gmail need username and password so, I don't want that my data be in the code itself)
but I got this error of socketTimeOutException.
I can increase the timeout but then I cannot do anything until the response received, and it takes like 25 seconds.
and if I put the sending function in a thread it doesn't send the mail at all.
this is the code of the server:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONObject res = new JSONObject();
try {
System.out.println("Post ForgotMypass");
Mongo mongo = new Mongo(LogIn.host, 27017);
DB db = mongo.getDB("Users");
DBCollection collection = db.getCollection("usersCollection");
// get a myUser object and cheack for jobs
String json = request.getParameter("JSONObj");
JSONParser jp = new JSONParser();
JSONObject temp = (JSONObject) jp.parse(json);
String mail = (String) temp.get("mail");
if (mail != null) {
BasicDBObject searchQuer = new BasicDBObject();
searchQuer.put("Mail", mail);
DBObject Item = collection.findOne(searchQuer);
if (Item != null) {
JSONParser jp2 = new JSONParser();
JSONObject Is = (JSONObject) jp2.parse(Item.toString());
JSONObject I = (JSONObject) Is.get("_id");
String id = (String) I.get("$oid");
if (id != null) {
String Dmail = URLDecoder.decode(mail, "UTF-8");
SendMailSSL.SendMail(Dmail, 4, id);
StringWriter out = new StringWriter();
res.put("Status", "true");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
System.out.println("mail sent succesfully");
} else {
StringWriter out = new StringWriter();
res.put("Status", "falseNoMail");
System.out.println("ver false no mail");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {
StringWriter out = new StringWriter();
res.put("Status", "ObjectdoesntExists");
System.out.println("ver ObjectdoesntExists");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} else {// id is null
StringWriter out = new StringWriter();
res.put("Status", "falseIdNUll");
System.out.println("ver falseIdNUll");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
} catch (Exception e) {
e.printStackTrace();
StringWriter out = new StringWriter();
res.put("Status", "false");
System.out.println("ver false");
res.writeJSONString(out);
response.getOutputStream().println(out.toString());
}
}
and:
public static void SendMail(String to, int typeOfMessage, String UserID) {
Properties props = new 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");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("adress"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
/*
* all the type of messages
*/
if (typeOfMessage == 1) {
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 2){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 3){
message.setSubject("title");
message.setText("text");
}else if (typeOfMessage == 4){
message.setSubject("title");
message.setText("text");
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
so, somebody has an idea how to avoid that problem.
more specific , to send the mail via the server but after that, I sent the response somehow to the android client, so he doesn't have to wait for 25 seconds.
thanks

Your android app should send the request in a separate thread, because sending it through the main thread will block the GUI of your app. The Tomcat-Server handles requests in different threads by default. Thus you need not starting separate threads inside of the request handling. You can start a new thread like this (see docs for java.lang.Thread):
Thread theThread = new Thread(new Runnable() {
#Override
public void run() {
// send the request to the tomcat server
}
});
theThread.start();

Related

Java Constructor not defined

Trying to send an email through my test, it calls on this class as the main one.
public class SendMail{
public SendMail(String fromMail,String tomail, Exception e )
{
Properties props = new 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");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc123#gmail.com","testpw");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromMail));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(tomail));
message.setSubject("xxxxx");
message.setText("xxxxx"+ ExceptionUtils.getStackTrace(e) );
Transport.send(message);
System.out.println("Done");
}
catch (MessagingException ex) {
throw new RuntimeException(ex);
}
}
public SendMail(String string, String line) {
So I want to call this in my other class, to be able to pull a list of emails from a txt file so it will email everything on the list. That code is:
String fileName = "/xxx/xxx/xxx/text.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) !=null) {
new SendMail("abcd#gmail.com", line);
}
}
catch (IOException e) {
e.printStackTrace();
}
The problem is that it's telling me the constructor SendMail(String, String) is undefined.
My orginal code works but this only allows me to send hard coded emails.
try{
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("senderemail","reciveremail",e); }
}
Why won't it accept my constructor?
EDIT: The consturctor was not wrong. I was! I found the reason why It wouldn't work and solved my issue. This is the code I'm using now that works.
String fileName = "/Users/cdolan/Desktop/liness.txt";
String Email = "";
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
while ((Email = br.readLine()) !=null)
{
<Test code here goes here>
}
}
catch(Exception e)
{
e.printStackTrace();
new SendMail("email123#gmail.com",Email,e); }
}
The problem is that you only define the method SendMail(String fromMail,String tomail, Exception e) so you cant call a method that is not defined.
You need to define and implement the methodSendMail(String fromMail,String tomail,) so you can call it!
Another question should be: for what reason do you need to pass the exception as a input param?
The constructor you have specified takes an Exception as an argument (for what reason??). This exception argument is missing when you create a new object.

Executing java mail program from unix box machine in which java is installed

I have the below java program which I am executing from eclipse under windows and it is working perfectly. Now I want to create a jar of it which I can make it from eclipse it self by creating a jar option now p, as I want to execute the same program from unix box machine in which java is installed please advise how I will test this same program from unix box machine in which java is installed and jdk is set, shall I go for jar creation process.
public class SSendEmail {
MimeMessage mimeMessage = null;
public static void main(String[] args) throws Exception, IOException, Exception {
String smtpHost = "11.1620.90.520";
String mailSmtpPort = "192381";
String mailTo[] = {"ena#rdbs.com"};
String mailCc[] = {"sena#rdbs.com"};
postEmailForBrokerageNotification(mailTo, mailCc, "k",
"testSubject", "Body123", smtpHost, mailSmtpPort);
}
//Send email for broker post pay email notification
public static void postEmailForBrokerageNotification(String mailTo[], String mailCc[], String from, String subject, String text, String smtpHost, String mailSmtpPort) throws Exception, DocumentException, IOException {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.store.protocol", "imaps");
properties.put("mail.smtp.port", mailSmtpPort);
properties.put("mail.smtp.auth", "false");
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
//Enable for debuging
emailSession.setDebug(true);
Message emailMessage = new MimeMessage(emailSession);
if (mailTo != null) {
InternetAddress[] addressTo = new InternetAddress[mailTo.length];
for (int i = 0; i < mailTo.length; i++) {
addressTo[i] = new InternetAddress(mailTo[i]);
}
emailMessage.setRecipients(RecipientType.TO, addressTo);
}
InternetAddress[] addresscc = new InternetAddress[mailCc.length];
for (int i = 0; i < mailCc.length; i++) {
addresscc[i] = new InternetAddress(mailCc[i]);
}
emailMessage.setRecipients(RecipientType.CC, addresscc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
emailMessage.setContent(text, "text/html");
//Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// attachment part
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\sd-Spec_for_Data-Mapping_P3--SARALE_RETURNswap.xls";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
throw new Exception(messagingException.getMessage());
}
}
}

user is receiving same email twice in java

I am using the code below to send emails using java ,my project is running on a tomcat server.
the problem that user is receiving same email twice.
after some research it seems that java is sending email twice,any one can help me how I handle it?
Properties props;
Session session;
try {
props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "....");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.connectiontimeout", "2000");
props.put("mail.smtp.timeout", "2000");
props.setProperty("charset", "utf-8");
session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// session.setDebug(true);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
if (!to.equals("") && to != null) {
String[] toArray = to.split(";");
InternetAddress[] toList = new InternetAddress[toArray.length];
for (int i = 0; i < toArray.length; i++) {
toList[i] = new InternetAddress(toArray[i]);
}
message.addRecipients(Message.RecipientType.TO, toList);
}
if (!cc.equals("") && cc != null) {
String[] ccArray = cc.split(";");
InternetAddress[] ccList = new InternetAddress[ccArray.length];
for (int i = 0; i < ccArray.length; i++) {
ccList[i] = new InternetAddress(ccArray[i]);
}
message.addRecipients(Message.RecipientType.CC, ccList);
}
message.setSubject(subject);
//message.setText(emailBody);
message.setContent(emailBody, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
A way to solve errors when sending an email and, moreover, when you want to do something that has been already done from someone else, is by using a library. Open source libraries are used from a lot of developers and their bugs are all the times less than a custom source code. I would suggest you to use Apache commons Email Library.
Using this link you can find a lot of examples.

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

While loop executing infinite times in java for LogMonitor

I am working on a project where a java program records the changes made to the text file, writes it to other log file and sends it via email. The problem I am facing is the while loop used for monitoring changes has no break.
If I put the code of mailing inside while loop the mail goes in infinite loop.
If I put the code outside while loop, main can't reach there because while is in infinite loop. I need a break condition and I cant figure it out. Can anyone help?
import java.util.Properties;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class LogMonitor {
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("D:/test.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {
String line = br.readLine();
if (line == null)
{
Thread.sleep(1*1000);
} else
{
byte[] y = line.getBytes();
File g = new File("D:/abc.txt");
try (OutputStream f = new FileOutputStream(g,true))
{
f.write( y );
}
}
String to="abcde#gmail.com";//change accordingly
final String user="vwxyz#gmail.com";//change accordingly
final String password="xxxxxxx";//change accordingly
// final String d_port = "465";
//1) get the session object
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new 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");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user,password);
}
});
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Alert! Changes made to your file");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "D://abc.txt";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {
System.out.println(ex);
}
}
}}
First Move Sending email ail block to seperate method.
I just cut and pasted your code ..
public static void sendEmail() {
String to = "abcde#gmail.com";// change accordingly
final String user = "vwxyz#gmail.com";// change accordingly
final String password = "xxxxxxx";// change accordingly
// final String d_port = "465";
// 1) get the session object
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new 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");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// 2) compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Message Alert! Changes made to your file");
// 3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
// 4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "D://abc.txt";// change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// 5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
// 6) set the multiplart object to the message object
message.setContent(multipart);
// 7) send message
Transport.send(message);
System.out.println("message sent....");
}
catch (MessagingException ex) {
System.out.println(ex);
}
}
Then add boolean to mark changes in main like..
Note isFileChanged used to send email the changes captured.
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("D:/test.txt");
BufferedReader br = new BufferedReader(fr);
boolean isFileChanged = false;
while (true) {
String line = br.readLine();
if (line == null) {
if (isFileChanged){
isFileChanged = false;
sendEmail();
}
Thread.sleep(1 * 1000);
}
else {
isFileChanged = true;
byte[] y = line.getBytes();
File g = new File("D:/abc.txt");
try (OutputStream f = new FileOutputStream(g, true)) {
f.write(y);
}
}
}
}

Categories