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

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.

Related

Sending Mail with PlayFramework

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

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.

unable to send mail from java program authentication fail errorauthentication fail error

I am unable to send mail -- the program is throwing an authentication error
package com.gmc.registration.util;
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MailWithAttachement {
private String sender;
private String addressee;
private String subject;
private String nameOfAttachedFile;
private String filePath;
private String body;
private String contentType;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private transient String SMTP_AUTH_USER = "";
private transient String SMTP_AUTH_PWD = "";
public MailWithAttachement(final String sender, final String addressee, final String subject, final String nameOfAttachedFile, final String filePath, final String body, final String contentType) {
this.sender = sender;
this.addressee = addressee;
this.subject = subject;
this.nameOfAttachedFile = nameOfAttachedFile;
this.filePath = filePath;
this.body = body;
this.contentType = contentType;
}
public int send() {
int flag = 0;
final ResourceBundle resource = ResourceBundle.getBundle("com.gmc.student.resourseprop.student");
final Properties mailServerProperties = new Properties();
mailServerProperties.put("mail.smtp.host", resource.getString("mail.smtp.host"));
mailServerProperties.put("mail.smtp.port", resource.getString("mail.smtp.port"));
mailServerProperties.put("mail.smtp.auth", resource.getString("mail.smtp.auth"));
mailServerProperties.put("mail.smtp.sendpartial", resource.getString("mail.smtp.sendpartial"));
final Authenticator auth = new SMTPAuthenticator(resource.getString("mail.smtp.username"), resource.getString("mail.smtp.password"));
final Session session = Session.getDefaultInstance(mailServerProperties, auth);
// final Session session = Session.getInstance(mailServerProperties);
// final Session session = Session.getDefaultInstance(mailServerProperties);
final MimeMessage messageToSend = new MimeMessage(session);
try {
messageToSend.setFrom(new InternetAddress(this.sender));
messageToSend.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addressee));
messageToSend.setSubject(this.subject);
final BodyPart bodyText = new MimeBodyPart();
bodyText.setContent(this.body, this.contentType);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyText);
if (this.nameOfAttachedFile != null && this.filePath != null && !"".equals(this.nameOfAttachedFile) && !"".equals(this.filePath)) {
addAttachments(multipart);
}
messageToSend.setContent(multipart);
Transport.send(messageToSend);
flag = 1;
} catch (MessagingException exception) {
} catch (Exception excp) {
}
return flag;
}
private void addAttachments(final Multipart multipart) {
try {
final BodyPart attachment = new MimeBodyPart();
DataSource dataSource = new FileDataSource(this.filePath + this.nameOfAttachedFile);
attachment.setDataHandler(new DataHandler(dataSource));
attachment.setFileName(this.nameOfAttachedFile);
multipart.addBodyPart(attachment);
} catch (MessagingException excp) {
}
}
public static boolean emailvalidation(final String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {
private SMTPAuthenticator(final String username, final String password) {
SMTP_AUTH_USER = username;
SMTP_AUTH_PWD = password;
}
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
}
}
public static void main(String[] args) {
new MailWithAttachement("ash.k#test.com", "xxh.k#test.com", "sub", null, null, "<h1>This is a test</h1>"
+ "", "text/html").send();
}
}
prop file
mail.attachement.filepath=E:/test/attchedFiles/
mail.smtp.host=mail.test.com
mail.smtp.port=587
mail.smtp.username=ash.t
mail.smtp.password=123456
mail.smtp.auth=true
mail.smtp.sendpartial=true
As you haven't given a verbose of the exception, i'm posting my module that i have been using in production, it seems to work pretty well with gmail accounts.
/**
GmailSmtpSSL emailNotify = new GmailSmtpSSL(cred[ID], cred[PASS]);
emailNotify.sendMailTo("self","Testing AlfaDX Gmail module", "Yes it works");
**/
import java.text.SimpleDateFormat;
import java.util.Calendar;
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 GmailSmtpSSL {
GmailSmtpSSL(String username,String password) {
usern = username;
pass = password;
setDebugMsg("Setting user name to : "+usern);
setDebugMsg("Using given password : "+pass);
props = new Properties();
setDebugMsg("Setting smtp server: smtp.gmail.com");
setDebugMsg("Using SSL at port 465 auth enabled");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.user", usern);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
setDebugMsg("Session initialization complete");
}
public void destroy() {
props.clear();
props = null;
usern = null;
pass = null;
session = null;
}
public void sendMailTo(String to, String sub, String body)
throws MessagingException {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss a");
String dateToday = formatter.format(currentDate.getTime()).toLowerCase();
if (to.equals("self"))
to = usern;
setDebugMsg("Composing message: To "+to);
setDebugMsg("Composing message: Subject "+sub);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(usern));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("PinguBot: "+dateToday+" "+sub);
message.setText(body);
setDebugMsg("Attempting to send...");
Transport transport = session.getTransport("smtps");
transport.connect("smtp.gmail.com", 465, usern, pass);
Transport.send(message);
transport.close();
}
catch(MessagingException me) {
setDebugMsg(me.toString());
throw new MessagingException(me.toString());
}
setDebugMsg("Mail was send successfully");
}
public String getDebugMsg() {
String msg = new String(debugMsg);
debugMsg = " ";
return msg;
}
private static void setDebugMsg(String msg) {
debugMsg += msg + "\n";
System.out.println(msg);
}
private static String debugMsg = "";
private String usern;
private String pass;
private Session session;
private static Properties props;
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(usern, pass);
}
}
}

Sending email using java app

Why can't this code send email? There are no errors, it just doesn't send.
package tips.mails;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
private String from;
private String to;
private String subject;
private String text;
public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
new SendMail("source", "dist","Subject", "Test Message!!!");
}
}
You instantiate a SendMail object and do nothing with it. Maybe you should also execute your send() method.
You forgot to call send. Try this
new SendMail("source", "dist","Subject", "Test Message!!!").send();

Categories