Sending Mail with PlayFramework - java

application.conf
play.mailer {
host=smtp.gmail.com
port=25
ssl=true
tls=false
user="wahid.****.com"
password="A******f"
debug=false
mock=false
}
build.sbt
"com.typesafe.play" %% "play-mailer" % "5.0.0"
My Controller
public class MySampleMail {
#Inject MailerClient mailerClient;
public void sendEmail() {
String cid = "1234";
Email email = new Email()
.setSubject("Simple email")
.setFrom("wahid.************.com")
.addTo("w***********.com")
.setBodyText("A text message");
mailerClient.send(email);
}
}
But This send(email) is giving Execution exception[[CompletionException: java.lang.NullPointerException]]

Try out this:
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Main
private static String USER_NAME = "+++++++++++++++"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "++++++++++"; // GMail password
private static String RECIPIENT = "++++++++++++++";
public static void mainMethod() {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
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.host", 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();
}
}
}

Related

how to send email from using outlook using a java api

I am using the below code to send email from outlook using java. But getting the error.
CODE:
public static void mail (){
// TODO Auto-generated method stub
//String host="POKCPEX07.corp.absc.local";
String host="POKCPEX07.corp.absc.local";
final String user="satpal.gupta#accenture.com";
String to="satpal.gupta#accenture.com";
//Get the session object
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.port", "587");
Session session=Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("SGupta#amerisourcebergen.com","******");
}
});
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.saveChanges();
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Test mail");
message.setText("This is test mail.");
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e) {e.printStackTrace();}
}
}
ERROR:
javax.mail.MessagingException: Could not connect to SMTP host: POKCPEX07.corp.absc.local, port: 587;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1227)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)
at javax.mail.Service.connect(Service.java:258)
at javax.mail.Service.connect(Service.java:137)
at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at TestEmail.mail(TestEmail.java:50)
at TestEmail.main(TestEmail.java:16)
package com.sendmail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
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 SendAttachmentInEmail {
private static final String SERVIDOR_SMTP = "smtp.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx#xxx.com"; //Cofig Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password
private final String from = "xxxx#xxx.com";
private final String to = "xxxx#xxx.com";
private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";
public void sendEmail() {
final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
}
});
try {
final Message message = new MimeMessage(session);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress(from));
message.setSubject(subject);
message.setText(messageContent);
message.setSentDate(new Date());
Transport.send(message);
} catch (final MessagingException ex) {
System.out.println(" "+ex);
}
}
public Properties getEmailProperties() {
final Properties config = new Properties();
config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", SERVIDOR_SMTP);
config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
return config;
}
public static void main(final String[] args) {
new SendAttachmentInEmail().sendEmail();
}
}
As posted by you in comments above, it looks like your SMTP is not configured and by looking your exception - you are using gmail.
Follow this link to configure your SMTP.

Java ssl email sends to spam and not inbox

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
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 {
private static String hostname;
private static String username;
private static String password;
private static String sendTo;
private static String sentFrom;
private static String emailBody;
// sendSLLEmail()
public String sendSLLEmail(String hostname, String username,
String password, String sendTo, String sentFrom,String subject, String emailBody) {
try {
SendEmail.hostname = hostname;
SendEmail.username = username;
SendEmail.password = password;
SendEmail.sendTo = sendTo;
SendEmail.sentFrom = sentFrom;
SendEmail.emailBody = emailBody;
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SendEmail.hostname);
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setContent(SendEmail.emailBody, "text/html; charset=utf-8");
message.setFrom(new InternetAddress(SendEmail.sentFrom));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(SendEmail.sendTo));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
return "1";
} catch (Exception e) {
e.printStackTrace();
return "-1";
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String usernameTest = SendEmail.username;
String passwordTest = SendEmail.password;
return new PasswordAuthentication(usernameTest, passwordTest);
}
}
}
When I use this code, I pass values to it as parameters. The e-mail gets sent and works well, but always lands up in my clients spam folder can anyone tell me how I can prevent this ?
When I run this code I use my own mail server, so I would pass all the correct parameters to the code then it connects to my mail server and then gets mailed to spam.

Sending two different emails at the same time using JavaMail API

I'm using JavaMail API to notify the administrator when there's data insertion in database
This works fine. The admin receives the notification of data entry.
However, I also need to notify the client by sending him a confirmation at the same time, but it does not work. The customer does not receive any confirmation. I also want to paste the confirmation number in the subject. Could it be related to port conflict?
EmailAdmin.sendEmail(to, subject, body);
EmailCustomer.sendEmail(EM, subjectsub, bodybod, CN);
EmailAdmin.java
package session;
import java.util.Date;
import java.util.Properties;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
#Stateless
#LocalBean
public class EmailAdmin {
private final int port = 465;
private final String host = "smtp.server.com";
private final String from = "admin#domain.com";
private final boolean auth = true;
private final String username = "admin#domain.com";
private final String password = "password";
private final Protocol protocol = Protocol.SMTPS;
private final boolean debug = true;
public void sendEmail(String to, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private final PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setSentDate(new Date());
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
}
}
}
EmailCustomer.java
package session;
import java.util.Date;
import java.util.Properties;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
#Stateless
#LocalBean
public class EmailCustomer {
private final int port = 465;
private final String host = "smtp.server.com";
private final String from = "admin#domain.com";
private final boolean auth = true;
private final String username = "admin#domain.com";
private final String password = "password";
private final Protocol protocol = Protocol.SMTPS;
private final boolean debug = true;
public void sendEmail(String EM, String subjectsub, String bodybod, String CN) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private final PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(EM)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject, CN);
message.setSentDate(new Date());
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
}
}
}

Trouble when i'm trying to send an email throught my aplication

I'm having some trouble with my aplication to send an email.
Main code
public static void main(String[] args) throws EmailException, IOException {
ConfiguracaoEmail emailConfig = new ConfiguracaoEmail(new Filial("matriz", true));
emailConfig.setServidor("smtp.gmail.com");
emailConfig.setRemetente("emailFrom#gmail.com");
emailConfig.setTitulo("Teste");
emailConfig.setCodificacao("utf-8");
emailConfig.setAutenticacao("emailFrom#gmail.com");
emailConfig.setSenha("senhaEmail");
emailConfig.setPortaSMTP(465);
emailConfig.setTLS(true);
List<String> emails = new ArrayList<String>();
emails.add("emailTo#gmail.com");
try {
SendMail mail = new SendMail("Teste", " - envio email", emails, emailConfig);
mail.start();
} catch (EmailException e) {
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
}
}
The class ConfiguracaoEmail is just to auxiliate to pass the information.
Class SendEmail
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class SendMail extends Thread {
private HtmlEmail email;
public SendMail(String subject, String message, List<String> mailTo, ConfiguracaoEmail config) throws EmailException, IOException {
this.email = emailConfig(config);
email.setSubject(subject);
addTo(mailTo);
}
private void addTo(List<String> mailTo) throws EmailException {
for (String mail : mailTo) {
email.addTo(mail);
}
}
public HtmlEmail getEmail() {
return email;
}
public void setEmail(HtmlEmail email) {
this.email = email;
}
private HtmlEmail emailConfig(ConfiguracaoEmail cfg) throws EmailException {
HtmlEmail email = new HtmlEmail();
email.setDebug(cfg.getDebug());
email.setTLS(cfg.getTLS());
email.setSSL(true);
email.setHostName(cfg.getServidor());
email.setFrom(cfg.getRemetente(), cfg.getTitulo());
email.setCharset(cfg.getCodificacao());
email.setAuthentication(cfg.getAutenticacao(), cfg.getSenha());
email.setSmtpPort(cfg.getPortaSMTP());
email.setSSL(false);
return email;
}
#Override
public void run() {
try {
email.send();
} catch (EmailException e) {
throw new RuntimeException(e);
}
}
}
Someone have any idea what could possible be happening? It doesn't show any error. The email just isn't sent. (Obs: The code is not just it. I just pick the part revelant to the email)
The following code may solve your problem, its worked for me
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "xxxxx"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "xxxxx"; // 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 = "Welcome to JavaMail!";
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");//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();
}
}
}
if its not working ,check your jar files
The issue was in the emailConfig method and specifically the following line:
email.setSSL(false);
Removing this line solved the problem in my case.

Java Mail not working

I am sending an email using the Java mail api. And it works fine when I send an email to myself from my own account. But when I try to send an email to a different account it gives me an authentication exception. Here is my code:
package nl.cofely.MailHandler;
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String[] _to;
private String _from;
private String _pass;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private boolean testMessageSend;
private Multipart _multipart;
static Mail instance;
private Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_subject = "Person in trouble !"; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a
// handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap
.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public static Mail getInstance(){
if(instance == null){
instance = new Mail();
}
return instance;
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if (_debuggable) {
props.put("mail.debug", "true");
}
if (_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
_body = _body + " gebruiker: " + _from;
this._body = _body;
}
// more of the getters and setters …..
public boolean send() throws Exception {
Properties props = _setProperties();
if (!_user.equals("") && !_pass.equals("") && _to.length > 0
&& !_from.equals("") && !_subject.equals("")
&& !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
if(testMessageSend){
_multipart.removeBodyPart(0);
}
_multipart.addBodyPart(messageBodyPart,0);
System.out.println(_multipart.getBodyPart(0));
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public boolean sendTestMail() throws Exception{
setSubject("Testing mail configuration!");
setBody("Dit is een email voor het testen van de email configuratie ");
testMessageSend = send();
setBody("");
return testMessageSend;
}
public void setFrom(String _from){
this._from = _from;
}
public String getFrom(){
return _from;
}
public void setPass(String _pass){
this._pass = _pass;
}
public String getPass(){
return _pass;
}
public void setSubject(String _subject){
this._subject = _subject;
}
public String getSubject(){
return _subject;
}
public void setUser(String _user){
this._user = _user;
}
public String getUser(){
return _user;
}
public void updateUserInfo(String[] _to, String _from, String _pass){
this._to = _to;
this._from = _from;
this._pass = _pass;
this._user = _to[0].substring(0, _to[0].lastIndexOf("#"));
}
}
Can anyone tell what is going on here? Thanks
Try something like this:
public int sendMail(String reciever_email, String subject, String body) {
final String username = "YOUR USER EMAIL";
final String password = "PASSWORD";
Properties props = new Properties();
props.put("mail.smtp.user", username);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallbac k", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
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(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(reciever_email));
message.setSubject(subject);
message.setText(body);
Multipart multipart = new MimeMultipart("related");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html>HELLO</html>", "text/html");
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
Transport.send(message);
return 1;
} catch (Exception e) {
return 0;
}
}

Categories