Automating existing web application and email generated report - java

I do have a java web application that is used for storing data about issues we faces daily.
There are many users and each user will be inserting data into it daily and by the end of day we'll gather that particular days data and then mail it to everyone.
We are using the web app to do this. But as of now web app generates consolidated data for one day when I trigger it using a button press.
And the code written to create excel sheet drafts a excel sheet and this one i mail to everyone. This web application is being run on a server.
I wish to automate this process i.e. each night at some specified time it should automatically trigger the function and generate the excel sheet and it should mail it to everyone.
I don't have much idea about how to go forward so I thought first I'll write java code to send mail and later think about triggering the function at a particular time.
I would like to know whether is there any other better way to deal with my requirement. I'am open to suggestions.
Also, the code I have written to send the mail is not working. It is giving me exception and I tried almost everything I could find but nothing is working. Could someone help me in sorting out the error.
Here's the code :
package com.email;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "toemail#gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail#gmail.com";
final String username = "username";//change accordingly
final String password = "password";//change accordingly
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Now set the actual message
message.setText("Hello, this is sample for to check send " +
"email using JavaMailAPI ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Exception that I am receiving is :
Exception in thread "main" java.lang.RuntimeException: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.tutorialspoint.SendEmail.main(SendEmail.java:62)
Caused by: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.UnknownHostException: smtp.gmail.com
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
at com.email.SendEmail.main(SendEmail.java:57)
Caused by: java.net.UnknownHostException: smtp.gmail.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 7 more

According to the logs you cannot reach the gmail smtp. Are you maybe behind a proxy/firewall? Did you try pinging the smtp?
For running the tasks automatically you just need to add a scheduling framework to run the code at a certain time.
You could use quartz for example

Related

Java Mail API fails intermittently

I have created automated email report using java mail api which needs to be triggered everyday after a batch file run.Although it works fine most of the times,at times it gives exception javax.mail.MessagingException: Could not connect to SMTP host: my host name, port: 25; nested exception is: java.net.ConnectException: Connection refused.This is not due to authentication issue as i use the same credentials whenever i sent the email.
I am not sure why java mail api fails intermittently.Can i get some suggestion to debug the issue?
I am using the below code snippet -
String to = "xyz#gmail.com";//change accordingly
String from = "abc#mydomain.com";//change accordingly
final String username = "abc";//change accordingly
final String password = "*****";//change accordingly
String host = "My SMTP server";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Testing Subject");
message.setText("message to stakeholders");
Transport.send(message);
}
It's a good idea to check logs on the mail server to see possible cause of the refusal - especially since you know WHEN failed attempts were made at.
If JavaMail can't connect "sometimes" with "connection refused", the possibilities are:
The server is actually down.
The server is up, but too busy to accept new connections.
The server is up, but is rejecting connections for some policy reason, e.g., you've connected too frequently.
Some firewall or anti-virus program has rejected the connection.
Check the server configuration and log files. If there's nothing on the server indicating that it's rejecting connections, check the client.

Strange Behaviour of java mail sending in JAVAEE and JAVA Project

Hi I am trying to implement the e-mail sending through my Web Application. This is how my java class is:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import javax.activation.*;
public class SendMail{
public void sendEmail(String fromEmail, String toEmail,String subject, String message) throws MessagingException{
System.setProperty("java.net.preferIPv4Stack" , "true");
Properties props = System.getProperties();
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", "587");
Session mailSession = Session.getInstance(props,null);
mailSession.setDebug(true);
Message mailMessage = new MimeMessage(mailSession);
mailMessage.setFrom(new InternetAddress(fromEmail));
mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
mailMessage.setSubject(subject);
mailMessage.setText(message+"This E-Mail was sent to you");
Transport.send(mailMessage);
}
}
The above code absolutely works fine when I write a main method in the class specified above and run it as java application or through any other class having main method. But it shows java.net.SocketException: Network is unreachable: connect] with root cause
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; when I run my web application and calling the sendMail method into that class having no main method. How do I solve it. Any help much appreciated.
Can anybody give any update on this error Exception in thread "main" javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 5.7.0 Authentication required. Even if I do password authentication false why does it asks for it. I solved all the previous errors and getting the new one like this. Any help much appreciated.

how to send email from our mail server in java

This is my code...
final String from = "demo#ourmail.com";
final String password = "demo1234";
Properties props = new Properties();
props.put("mail.smtp.host", "14.141.48.131");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
String subject = "Registeration conformation for happy shopping";
String to = demo#gmail.com;
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setContent("<html>\n"
+ "<body>\n"
+ "\n"
+ "<p> you are successsfully login</p>"
+ "</body>\n"
+ "</html>", "text/html");
Transport.send(message);
System.out.println("end of utility");
} catch (Exception ex) {
System.out.println(ex);
}
After running this, an exception is generated, i.e.
javax.mail.MessagingException: Could not connect to SMTP host: 14.141.48.131, port: 25;
nested exception is:
java.net.SocketException: Permission denied: connect
Please suggest how I can handle this exception.
Your Java code looks fine. Successfully communicating with your mail server is the hard part.
Maybe you're running Java 7, and maybe (per this link) the problem can be resolved by setting this simple JVM parameter: -Djava.net.preferIPv4Stack=true.
Definitely check your firewall (make sure the SMTP port is open between your Java program and the mail server), and definitely check for any anti-virus programs that might be restricting SMTP on the mail server.
Or maybe your mail server requires SSL/TLS encrypted SMTP port 465 (instead of SMTP port 25).
Then again, maybe your ISP/internet provider doesn't permit SMTP at all.
There are a million possibilities. Talk with your network administrator. And try these SMTP troubleshooting tips (independent of debugging your Java program):
http://www.port25.com/how-to-check-an-smtp-connection-with-a-manual-telnet-session-2/
PS:
Never ever EVER!!!! post real usernames, passwords ... or IP addresses. In ANY external forum.

Email sending not working using Apache James

I am trying to send email using apache james but the emails are not getting delievered. Below is my code.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class test {
public static void main(String args[]) throws Exception {
String user = "test";
String password = "test";
String fromAddress = "test#localhost";
String toAddress = "test#gmail.com";
Properties properties = new Properties();
properties.put("mail.smtp.host", "localhost");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.username", user);
properties.put("mail.smtp.password", password);
properties.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(properties, null);
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress));
message.setSubject("Email from our JAMEs");
message.setText("hiiiiii!!");
Transport.send(message);
System.out.println("Email sent");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Also test user is added in apache james having password test. Requesting you to kindly help me out in the same.
I think problem caused by this:
Email servers before accepting any mail do a reverse dns query. They check the ip for domain that the email came from and the ip that email is really came from.
If ip of domain and ip of email sender does not match, mail servers think that email is junk or spam.
Here since your domain (localhost) is not a valid address when Email server send a reverse dns query does not get an IP and think your mail is junk or spam.
For more information check this: http://wiki.junkemailfilter.com/index.php/Fixing_Reverse_DNS
I faced the same problem. What I did:
Go to the path : \apps\james\conf
Open for edit the filename 'james-fetchmail.xml'
Change "fetchmail" from false to true as:
Restart the Apache James Server.
You would see the following messages printed on the console after you start the server:
James Mail Server 2.3.2
Remote Manager Service started plain:4555
POP3 Service started plain:110
SMTP Service started plain:25
NNTP Service started plain:119
FetchMail Started
Now, run your program. It should work!
Did you added the domain "localhost"?
If not, add the domain first, and after create the users.
$ james-cli AddDomain -h 127.0.0.1 localhost
check if domain exists
$ james-cli ListDomains -h 127.0.0.1
And, how do you started james? Using james.bat?

sending an email from java [duplicate]

This question already has answers here:
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
(14 answers)
Sending Email using java program [duplicate]
(3 answers)
Closed 5 years ago.
i have been trying to send an email from my servlet. I tried to see how this can be done in the internet. But, in all the codes that I came across, none of them used the senders password to send the mail.
This means anyone can send an email from anyone's account. have I got it wrong or what is the actual matter?
Exception in thread "main" javax.mail.MessagingException: Could not connect to S
MTP host: localhost, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:41
2)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:189)
at Email1.main(Email1.java:19)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI
mpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja
va:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket
Impl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java
:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:612)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160
)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
You're right in a way. Anyone can send am email pretending to be anybody else if smtp server doesn't require authentication ;-) Fortunately most servers out there do require authentication.
I didn't quite get what you're trying to achieve here. Do you have your own smtp server, or do you want to allow users to send mail from an account they already have (e.g. from gmail.com). In both cases you'll probably like to see JavaMail API documentation. There is even a sample JavaMailServlet you may use as reference.
Here's a simple program that sends an email and uses user/pass to authenticate to smtp server (based on examples in JavaMail):
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail
{
public static void main(String[] args) throws MessagingException
{
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.example.com");
// props.setProperty("mail.smtp.auth", "true"); // not necessary for my server, I'm not sure if you'll need it
Session session = Session.getInstance(props, null);
Transport transport = session.getTransport("smtp");
transport.connect("user", "password");
Message message = new MimeMessage(session);
message.setSubject("Test");
message.setText("Hello :)");
message.setFrom(new InternetAddress("you#example.com"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("your-friend#example.com"));
transport.sendMessage(message, message.getAllRecipients());
}
}
Sending an e-mail from a servlet is something you might do when you have code that is running a report or needs to notify you of some event, in which case, that e-mail will be from a generic service account. If you want to use a client's e-mail credentials, you will have to request them or have an UI that allows your users to enter contact information. I think it is kind of iffy to be asking anyone for their e-mail password, however. I know I would not enter that information into someone's website, no matter how much I trusted their service. So I think you need to think more about your design and what your expecations are as opposed to simply how to do it with code.

Categories

Resources