Strange Behaviour of java mail sending in JAVAEE and JAVA Project - java

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.

Related

Automating existing web application and email generated report

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

JavaMail: Sending Mail via 1und1 gives 550 Error

A friend of mine has a new website and i build him a tool to organize email-addresses and send newsletters (HTML-Messages). Therefore i use the javax.mail library. While developing i sent all mails from my gmail account and it worked fine. But now, for "production", i want to send the mails from his domain, which is hosted by 1und1.
I am able to connect successfully to the 1und1 smtp-Server, but as soon as i send a mail, i get the following errors:
com.sun.mail.smtp.SMTPSenderFailedException: 550-Requested action not taken: mailbox unavailable
550 invalid DNS MX or A/AAAA resource record
When sending from the online 1und1 webmailer, i can send to any mailadress without errors.
These are the props i set for mailing. Like i said, i can connect to the server with these information, but sending fails.
Properties props = new Properties();
// Zum Senden
props.setProperty("mail.smtp.starttls.enable" , "true");
props.setProperty("mail.smtp.host", configurationService.getMailHost()); // smtp.1und1.de
props.setProperty("mail.smtp.auth", configurationService.getMailAuth().toString()); // true
props.setProperty("mail.smtp.port", configurationService.getMailPort()); // 587
props.setProperty("mail.smtp.user", user);
props.setProperty("mail.smtp.password", pass);
return Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(props.getProperty("mail.smtp.user"),
props.getProperty("mail.smtp.password"));
}
});
Thanks for help!
Edit: When Debugging the Session, i get the following line just before the exception occurs:
MAIL FROM: <USER#LAPTOP-Name.fritz.box>
How can i change this to something accepted?

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.

Trouble sending via gmail's SMTP server with Java

One of my customers is using Gmail for business (part of Google Apps) and I had to reconfigure the website I've developed so it would match the new credentials. After a bit of struggle due to TLS errors, I've managed to make the code work on localhost and on my test server (both Apache Tomcat 5.5). Everything was going smooth until I had to move it on his server (another Tomcat 5.5 as the hosting company told me). On the client's server I get the following error:
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.io.IOException: Couldn't connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port: smtp.gmail.com, 465; Exception: java.lang.reflect.InvocationTargetException
The strange thing is that on localhost and the test server the port 465 works fine, and the guys from hosting said that port is opened on their server.
The code that connects to the mailserver is:
private void initConfigParams() throws CMSGeneralException {
try {
props = System.getProperties();
String smtpHost = Messages.getDBConfString("mail.smtp.host");
String mailPort = Messages.getDBConfString("mail.smtp.port");
String socketFallback = Messages.getDBConfString("mail.smtp.socketFactory.fallback");
String enableTls = Messages.getDBConfString("mail.smtp.starttls.enable");
String authSmtp = Messages.getDBConfString("mail.smtp.auth");
String tlsRequired = Messages.getDBConfString("mail.smtp.stattls.required");
String sktFactory = Messages.getDBConfString("mail.smtp.socketFactory.class");
props.put("mail.smtp.starttls.enable", enableTls);
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", authSmtp);
props.put("mail.smtp.starttls.required", tlsRequired);
props.setProperty("mail.smtp.socketFactory.class", sktFactory);
props.setProperty("mail.smtp.socketFactory.fallback", socketFallback);
props.setProperty("mail.smtp.port", mailPort);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.put("mail.transport.protocol", Messages.getDBConfString("mail.transport.protocol"));
Authenticator auth = null;
userName = Messages.getDBConfString("mail.username");
userPassword = Messages.getDBConfString("mail.userpassword");
if (!CMSUtils.isEmptyString(userName) && !CMSUtils.isEmptyString(userPassword)){
/* props.put("mail.smtp.auth", "true"); */
auth = new SMTPAuthenticator(userName, userPassword);
}
session = Session.getDefaultInstance(props, auth);
session.setDebug(false);
address = new InternetAddress[1];
address[0] = new InternetAddress(recipients);
mbText = new MimeBodyPart();
mbText.setContent(text, "text/html");
mp = new MimeMultipart();
mp.addBodyPart(mbText);
} catch (MessagingException e) {
e.printStackTrace();
throw new CMSGeneralException();
}
}
With the following .properties file
mail.smtp.starttls.enable=true
mail.smtp.host=smtp.gmail.com
mail.smtp.auth=true
mail.smtp.starttls.required=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false
mail.smtp.port=465
mail.transport.protocol=smtps
mail.username=website#example.com
mail.userpassword=password
mail.from=website#example.com
mail.to=mail#example.com
I tried the other ports for GMail, 587, but it doesn't work on any of the servers. Not even port 25 won't do the trick.
So, what am I doing wrong, and what should I do to make the mailing work?
Get rid of all the socket factory properties; if you're using a reasonably recent version of JavaMail you don't need them. See the JavaMail FAQ for how to configure JavaMail to access Gmail. You'll also find debugging tips there if it still doesn't work.
Also, change Session.getDefaultInstance to Session.getInstance.
And finally, if you're setting "mail.transport.protocol" to "smtps", you need to set the other properties as "mail.smtps." properties, not "mail.smtp." properties.
It seems to you have problems with java.lang.reflect.InvocationTargetException. So, I mean it's not a network problem. May be you've specified some parameters wrong and JavaMail API routes couldn't invoke a method. May be you should also specify property mail.smtp.ssl.socketFactory.
Some documentation here http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html .

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?

Categories

Resources