I have Written a code for Sending mail having Attachment file but getting javax.mail.SendFailedException Exception . below is the code which I have written. Can anyone Correct me that why i am getting Exception
Below is Exception
java.lang.RuntimeException: 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.net.ConnectException: Connection timed out: connect
at sendMail.sendMail2.execute(sendMail2.java:102)
at sendMail.sel.main(sel.java:17)
Below is Mail Class
package sendMail;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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 sendMail2 {
public static void execute() throws Exception {
final String username = "sender#gmail.com";
final String password = "*********";
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");
props.put("mail.smtp.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("sender#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recepient#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "C:/Selenium Workspace/FMC360Automation/test-output/emailable-report.html";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Below is Basic Java Selenium program
package sendMail;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class sel {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gws_rd=cr,ssl&ei=sjPLVue4OI2IuATgkaWwCw");
try {
//Sendmail.execute("C:/Selenium Workspace/FMC360Automation/test-output/emailable-report.html");
sendMail2.execute();
driver.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Login to your google account using your gmail credential which you are using to send mail from selenium scripts. Then browse https://myaccount.google.com/security?hl=en#connectedapps and enable 'Allow less secure apps'
Related
I am wondering why the below basic java mail program is not working because I didn't get any errors as the program is executed just fine. Is there anything that I am doing wrong? Any help would be appreciated.I would also like to add that I also tried it using wrong username and password combination but still getting no error and the programs runs completely fine.
public class emailfromgmail {
public static void main(String[]args)
{
final String from = "username";
final String pass = "password";
String to = "recipient#gmail.com";
String host="smtp.gmail.com";
String subject = "java Mail";
String body = "example of java mail api using gmail smtp";
//get the session object
Properties p = System.getProperties();
p.put("mail.smtp.starttls.enable","true");
p.put("mail.smtp.host",host);
p.put("mail.smtp.user",from);
p.put("mail.smtp.password",pass );
p.put("mail.smtp.port", "587");
p.put("mail.smtp.auth","true");
Session session = Session.getInstance(p,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try{
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject(subject);
msg.setText(body);
Transport.send(msg);
System.out.print("message sent successfully");
}
catch(MessagingException e){
e.printStackTrace();
}
}
}
I had the same problem - I ran my program and put in a dialogue box in various places to see where it stopped doing anything. I still don't know what was wrong, but I tried a totally different approach and it worked. Instead of sending via TLS, I send via SSL. I used this website:
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
Their TLS didn't work - it just didn't do anything when I ran it. Their SSL worked like a charm!
Here is the code:
package com.mkyong.common;
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 SendMailSSL {
public static void main(String[] args) {
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("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to#no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Tried number of options found on google including stackoverflow but did not succeed:
package net.codejava.spring;
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) {
String to = "abc#gmail.com";
String from = "info#xyz.com";
// Get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.debug", "true");
properties.setProperty("mail.smtp.host", "smtp.xyz.com");
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("info#xyz.com", "test999");
}
});
// compose the message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message
Transport.send(message);
System.out.println("message sent successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I tried all I could do with it, please help me on this. Also, tried this one but failure again,
https://confluence.atlassian.com/jirakb/unable-to-send-mail-due-to-could-not-connect-to-smtp-host-297665338.html
I have read and tried all solution given in stackoverflow and in other various sites but still getting issue and getting exception.
Code :
import java.util.Properties;
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;
public class sendmail {
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public static void main(String args[]) throws AddressException,
MessagingException {
sendmail javaEmail = new sendmail();
javaEmail.setMailServerProperties();
javaEmail.createEmailMessage();
javaEmail.sendEmail();
}
public void setMailServerProperties() {
String emailPort = "587";//gmail's smtp port
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", "true");
emailProperties.put("mail.smtp.starttls.enable", "true");
}
public void createEmailMessage() throws AddressException,
MessagingException {
String[] toEmails = { "emailid#gmail.com" };
String emailSubject = "Java Email";
String emailBody = "This is an email sent by JavaMail api.";
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
for (int i = 0; i < toEmails.length; i++) {
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}
emailMessage.setSubject(emailSubject);
emailMessage.setContent(emailBody, "text/html");//for a html email
//emailMessage.setText(emailBody);// for a text email
}
public void sendEmail() throws AddressException, MessagingException {
String emailHost = "smtp.gmail.com";
String fromUser = "emailid";//just the id alone without #gmail.com
String fromUserEmailPassword = "test";
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserEmailPassword);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
System.out.println("Email sent successfully.");
}
}
When I debug code , it stop working at line : Transport transport = mailSession.getTransport("smtp");
I have added following JARs :
Mail.jar , pop3.jar , smtp-1.4.2.jar , Activation.jar , additional.jar
Full exception :
Exception in thread "main" javax.mail.NoSuchProviderException: smtp
at javax.mail.Session.getService(Session.java:764)
at javax.mail.Session.getTransport(Session.java:689)
at javax.mail.Session.getTransport(Session.java:632)
at javax.mail.Session.getTransport(Session.java:612)
at javax.mail.Session.getTransport(Session.java:667)
at javax.mail.Transport.send0(Transport.java:154)
at javax.mail.Transport.send(Transport.java:80)
at JannyaPaid_Device.sendmail.sendEmail(sendmail.java:68)
at JannyaPaid_Device.sendmail.main(sendmail.java:26)
Also I want to ask that firewall can prevent this things to send mail? As we have some firewall installed but I able to open and send mail thrugh gmail manually.
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 SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
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");
props.put("mail.smtp.port", "587");
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-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
For - Must issue a STARTTLS command(start transport layer security), you might need a certificate in the path(in JDK/JRE) and same on the Email server side as well.
I would like to send email without authentication using java.
Can someone help me?
With authentication, I do it as follows:
public void sendEmail() throws EmailException{
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.addTo("XXX#gmail.com", "XXXX");
email.setFrom("XXXX#gmail.com","XXXXX");
email.setSubject("testando . . .");
email.setMsg("testando 1");
email.setSSL(true);
email.setAuthentication("xxxxxx#gmail.com", "XXXXX");
email.send();
}
I forgot to say that i do not have a provider. i need an provider finally, i have emailFrom Subject and Message, and need send this email how?
If it is only for testing purposes, you may try Papercut. While it’s running, Papercut automatically picks up e-mail sent to the standard SMTP port (25) on any IP address. You just send mail from your application and switch to Papercut to review it.
Papercut # github:
https://github.com/ChangemakerStudios/Papercut/releases
import java.util.Date;
import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "127.0.0.1");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("admin#test.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("a#b.com"));
message.setSubject("Notification");
message.setText("Successful!", "UTF-8"); // as "text/plain"
message.setSentDate(new Date());
Transport.send(message);
}
}
import java.util.*;
import javax.mail.*;
public class SimpleEmail {
public static void main(String[] args) {
System.out.println("SimpleEmail Start");
String smtpHostServer = "smtp.gmail.com";
String toEmail = "XXXX#gmail.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(props);
try {
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress("n91eply#gmail.com", "NoReply-JD"));
msg.setReplyTo(InternetAddress.parse("n91eply#gmail.com", false));
msg.setSubject("SimpleEmail Testing Subject", "UTF-8");
msg.setText("SimpleEmail Testing Body", "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
System.out.println("Message is ready");
Transport.send(msg);
System.out.println("EMail Sent Successfully!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this example:
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd#gmail.com";
// Sender's email ID needs to be mentioned
String from = "web#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Via: tutorialspoint
Trying to get Play! Framework to send an email with an attachment. Code below works fine if I don't add the attachment to the message. I've tried both with Play's Mailer class and with the Apache Commons classes (as below), but in both cases, the page just sits there with a spinner (Chrome) and no email is received.
EmailAttachment attachment = new EmailAttachment();
attachment.setURL(new URL(base + "public/images/triangles.png"));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("test");
attachment.setName("test");
emailaddress = "test#test.com";
MultiPartEmail email = new MultiPartEmail();
email.setDebug(true);
email.addTo(emailaddress);
email.setFrom("Testing <test#test.com>");
email.setSubject("Testing email");
try
{
email.attach(attachment);
}
catch (EmailException ex)
{
System.out.println(ex.getMessage());
}
email.setMsg("test email");
email.send();
Im guessing you've already had a look at the Examples for Apache Commons and Sending e-mail - Play! Framework 1.1?
IMO I'd suggest using a well known library with loads of documentation and examples like JavaMail and their api.
Here are a few tutorials that will get you started immediately:
JavaMail quick start
Java Mail SMTPClient Example
Sending mail with attachment with javamail
An example of using the JavaMail to send a Email with attachment via gmail is:
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 SendMailTLS {
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
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");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Define message
MimeMessage message =
new MimeMessage(session);
message.setFrom(
new InternetAddress(from));
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(
"Hello JavaMail Attachment");
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Hi");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
HTH
References:
JavaMail API – Sending Email Via Gmail SMTP Example
http://www.jguru.com/faq/view.jsp?EID=30251