I am trying to send as email using JavaMail API, through my gmail account, but I am getting a javax.mail.MessagingException exception
The Code :
public static Result sendMail() {
Map < String, String[] > values = request().body().asFormUrlEncoded();
String toAddresses = values.get("toaddrs")[0];
String subject = values.get("subject")[0];
String body = values.get("body")[0];
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("samplemail#gmail.com", "samplepass");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("samplemail#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
return ok("sent");
} catch (MessagingException e) {
return ok("Error in sending email");
}
}
On debugging, I end up here in Service classs
which throws the exception : javax.mail.MessagingException: Host, username, and password must be specified.
Correct these common mistakes. If it still doesn't work, post the debug output.
The only differences that I can find with code that I am using to send to gmail (and which works) is this:
Properties props = System.getProperties();// get system props?
props.put("mail.smtp.socketFactory.fallback", "false");
and
msg.setSentDate(new Date());
you can also add: session.setDebug(true); this might give more clues.
On what line is the exception thrown?
Thanks for the answers. The problem turned out to be a weird one, at least for a newbie like me. Simply put, I had exjello libraries in my classpath. They were messing with my JavaMail API. Once I created a new project and copied my code there, it worked fine. Just to check, I copied the exjello jars to my new project's classpath and it stopped working.
From a layman's point of view, it doesn't seem to be a good idea for a jar file to mess with my execution even though i had not even imported the package to my class.
Related
I have an automated java mail application that sends automated mail to users when some important update occur in our database. It was working fine. However it started to give me errors and I realized that it's not working.
The error says:
"Please log in via your web browser and then try again.
Learn more at https://support.google.com/mail/bin/answer.py?answer=78754 l10sm7526045oev.7 - gsmtp"
The java mail application that I write is huge and contains some confidential values(password etc.), I decided to write a sample demo to show you what's going on. It gives me the same error. Please assume that javax.MAIL API has been imported to the project. Here is what I have:
public class MailDemo {
public static void main(String[] args) {
final String userName = "dummyEmail#gmail.com";
final String password = "dummyPassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");//Smtp server address
props.put("mail.smtp.port", "587");//port for the smtp server
Session session = Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("dummyEmail#gmail.com"));//from email address
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("dummyEmail#gmail.com"));//to email address
message.setSubject("My first Email");//Subject of the mail
message.setContent("<h1>This is a test email</h1>", "text/html; charset=utf-8");//Content of the mail
Transport.send(message);//send the message
System.out.println("Email Stiation:Done!");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Well, i found the problem. Actually the codes are correct. It's gmail. it blocks the sign in attempts.I think that gmail thinks the attempts are not real.
I have a program where I have a number of users which each could be sending emails from different email accounts.
When I try to use JavaMail to send emails. They always get sent out by the account of the user who sent an email first.
user1 = new User("dummy-email#gmail.com", "dumpass12");
user2 = new User("second-dummy#gmail.com", "secondpass12");
user1.sendMail(toAddress, subject, body);
user2.sendMail(toAddress, subject, body);
Now when I do something like this, the second user will send a message but it will come from the SAME mailbox as user1 (i.e. both messages will come from dummy-email#gmail.com).
Can somebody explain to me why this is happening? Do I have to close the connection somehow? How can I send the two emails and have them come from the different accounts? Please help me.
Here is my code which actually sends the email connecting to the user's gmail account.
public void sendMail(String toAddress, String subject, String body){
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(getUsername(),getPassword()); }
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getUsername()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toAddress));
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Replace Session.getDefaultInstance() with Session.getInstance(). To understand why, read the javadocs for those methods carefully.
The following is the program, which I am trying to send e-mail. The code is error free and I don't get any run time exception. But the code is unable to send e-mail. I have revised this code a lot but can't get what is actually wrong.
The sender and the receiver both have GMail accounts. The sender has 2-step verification process disabled. (I don't think it matters for the receiver. Does it?)
The code :
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
class tester {
public static void main(String args[]) {
Properties props = new Properties();
props.put("mail.smtp.host" , "smtp.gmail.com");
props.put("mail.stmp.user" , "username"); // username or complete address ! Have tried both
Session session = Session.getDefaultInstance( props , null);
String to = "me#gmail.com";
String from = "from#gmail.com";
String subject = "Testing...";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO , new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Working fine..!");
System.out.println("fine!!??");
} catch(Exception exc) {
System.out.println(exc);
}
}
}
Well, your code doesn't actually attempt to send the message. Take a look at Transport.send.
Here are some examples:
http://www.javapractices.com/topic/TopicAction.do?Id=144
http://www.vipan.com/htdocs/javamail.html
First of all, you forgot to call Transport.send() to send your MimeMessage.
Secondly, GMail needs to be configured to use TLS or SSL connection. The following needs to be added to your Properties (props):
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//To use SSL
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");
To connect to GMail SMTP, use the Transport.connect() method. I see you are not using any Transport at all in your code, so add this:
Transport transport = session.getTransport();
//Connect to GMail
transport.connect("smtp.gmail.com", 465, "USERNAME_HERE", "PASSWORD_HERE");
transport.send(msg);
Alternatively, you can create a Session by including a javax.mail.Authenticator as a parameter.
Example:
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("USERNAME_HERE", "PASSWORD_HERE");
}
});
I hope this helps you.
Resources:
Send email with SMTPS (eg. Google GMail) (Javamail)
JavaMail API – Sending email via Gmail SMTP example
I am writing a simple Java program to send mail, but am getting errors. Here's the code:
package mypackage;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// Send a simple, single part, text/plain e-mail
public class Sendmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "atul.krbhatia#gmail.com";
String from = "atul.krbhatia#gmail.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.gmail.com";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiatee a message
Message msg = new MimeMessage(session);
System.out.println("in try blk");
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
System.out.println("in catch block");
mex.printStackTrace();
}
}
}//End of class
Here's the errors:
221 2.0.0 closing connection d1sm3094152pbj.24
in catch block
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. d1sm3094152pbj.24
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at mypackage.Sendmail.main(Sendmail.java:48)
Gmail only supports SMTP over SSL/TLS.
Add
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You also need to login to the server:
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
A simple google search for "javamail gmail" will yield many example of how to use JavaMail with GMail, like this one. Google also has a configuration page listing the connection configuration that you'll need so you can double check the settings.
This URL May help:
http://sbtourist.blogspot.com/2007/10/javamail-and-gmail-its-all-about.html
It looks like the server is expecting SSL. There are several other questions on here where people are also trying to send mail through Gmail using Java, I recommend taking a look at them.
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
Must issue a STARTTLS command first. Sending email with Java and Google Apps
I want to send an email ussing an EJB but i the only thing i get in return in this exception:
java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
This is how my EJB looks like:
#Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB extends Authenticator implements IEmailServiceEJB {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx#gmail.com",
"xxxxxxx");
}
public void sendAccountActivationLinkToBuyer(String destinationEmail,
String name) {
// OUR EMAIL SETTINGS
String host = "smtp.gmail.com";// Gmail
int port = 465;
String serviceUsername = "xxxxxxx#gmail.com";
String servicePassword = "xxxxxxx";// Our Gmail password
Properties props = new Properties();
props.put("mail.smtp.user", serviceUsername);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
// Destination of the email
String to = destinationEmail;
String from = "xxxxxxx#gmail.com";
// Creating a javax.Session with the our properties
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
// From: is our service
message.setFrom(new InternetAddress(from));
// To: destination given
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Comfirm your account");
// Instead of simple text, a .html template should be added here!
message.setText("Welcome....... ");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, serviceUsername, servicePassword);
Transport.send(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I dont know why it keeps saying that the password is not specified? Does the SSLSocketFactory have something to do with it? Do i need to call the getPasswordAuthenticion() method somewhere, or calling the second method from my managed bean is all i need?
I don't know why your code isn't working, but you might want to take a look at this:
http://spitballer.blogspot.com/2010/02/sending-email-via-glassfish-v3.html
It shows an alternate method of configuring email in Java EE, which I think works much better. The connection details are configured at the container level, just like a container-managed database connection.
Read up on SPF and DKIM.
It's hard to know what's going wrong here, as your code is only 1/2 the needed information. The real issue is probably that your code doesn't fit your environment, and SPF and DKIM often is a reason that connecting to any public SMTP server and sending an email doesn't work.
At least after reading a little about SPF and DKIM, you'll be able to know if it is an issue in your case, or if it is not an issue in your case.