Error when sending mail in Java - java

i have desktop application and i face this error when sending mail javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection refused: connect
~code~
String host="smtp.mail.yahoo.com";
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host",host);
props.put("mail.smtp.host", host);
props.put("mail.stmp.user", "abc#yahoo.ca");//User name
//To use TLS
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.password", "mypassword"); //Password
props.put("mail.smtp.socketFactory.fallback", "false");
Session session1 = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "abc#yahoo.ca";
String password = "mypassword";
return new PasswordAuthentication(username, password);
}
});
MimeMessage msg = new MimeMessage(session1);
String from = "abc#yahoo.ca";
String subject = "Testing...";
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
msg.setSubject(subject);
Transport.send(msg);

YahooMail smtp port is 465 or 587
Add this :-
props.put("mail.smtp.port", "465");
or
props.put("mail.smtp.port", "587");

Did you find the JavaMail FAQ?
These entries will help:
How do I access Gmail with JavaMail?
How do I debug problems connecting to my mail server?
What are some of the most common mistakes people make when using JavaMail?

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

Related

JavaxException Unknown SMTP host Exception: mail.gmail.com

I am trying to send mail using Java code . The code is working fine when running on my personal PC . But on office network the exception of unknown SMTP host is appearing. Also my office pc is not able to ping smtp.gmail.com. PC firewall is closed as well.
Is there any other way to establish the connection? I am also providing my code below for reference.
mport javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.Authenticator;
public class otp {
String d_email = "email#gmail.com",
d_password = "password",
d_uname="uname",//your email password
d_host = "mail.outlook.com",
d_port = "587",
m_to = "target#gmail.com", // Target email address
m_subject = "Testing Mail programs",
m_text = "Hey, this is a test email.";
public otp() {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props,auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
System.out.println(1);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
System.out.println(3);
Transport transport = session.getTransport("smtp");
transport.connect(d_host, Integer.valueOf(d_port),d_uname , d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Transport.send(msg);
System.out.println("Message Sent succesfully");
} catch (Exception mex) {
mex.printStackTrace();
}
}
public static void main(String[] args) {
otp blah = new otp();
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}
}
I guess that you are behind the internal firewall/proxy of your office, it is very common to put the whole internal network of a company behind a central firewall or to check Outgoing/Incoming requests of the networks traffic a Dynamic Proxy Server.in that case, you can check it in the proxy settings of your pc.
internet explorer(or any browser)-> settings -> internet option -> Connections Tab -> LAN Settings.
for the granular analyses,please attach your code.
you are using a gmail account but you have provided a outlook host , try the following template:
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 SendEmailUsingGMailSMTP {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "xyz#gmail.com";//change accordingly
// Sender's email ID needs to be mentioned
String from = "abc#gmail.com";//change accordingly
final String username = "abc";//change accordingly
final String password = "*****";//change accordingly
// >> gmail host
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);
}enter code here
}
}

JavaMail exception : Could not connect to smtp host

I am trying to send an email using gmail in a java application. However I keep getting this error.
Severe: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
I hope someone can help me check if my code is wrong. I have been staring at it for awhile now and am quite stuck. Thanks!
My mailing code
public void sendEmail(String email){
String to=email;
String from="user#gmail.com";
String host="smtp.gmail.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.socketFactory.port", String.valueOf(465));
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.starttls.enabled", String.valueOf(true));
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//Session session = Session.getDefaultInstance(properties);
Session session= Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getpPasswordAuthentication(){
return new PasswordAuthentication("user#gmail.com", "password");
}
});
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
//set subject header field
message.setSubject("Password reset");
//set actual message
message.setText("Your password has been reset");
//send message
Transport.send(message);
System.out.println("Email has been sent");
}catch(MessagingException mex){
mex.printStackTrace();
}
}

I have this code to send mail from java showing error

package Controller;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
static String from = "******#gmail.com";
static String pass ="*****";
static String to = "****#gmail.com";
static String host = "smtp.gmail.com";
public static void main(String[] args) {
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("Ithis is a test");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
This code shows the error of:
javax.mail.MessagingException: Could not convert socket to TLS;
Could anyone help me, why can't it convert socket to TLS. What can I do to resolve the error?? Please do help.
By default, Gmail does not allow "less-secure" Apps to access your email.
In order to get your code to run:
Sign into your gmail account in a browser.
Go to https://www.google.com/settings/security/lesssecureapps
Set the Access for less secure apps option to Turn on
Either the certificate has not been installed in file cacerts or you might want to set the google smtp url as "trusted". try add this code
properties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
on the other note. You might need to set the javax.mail.Authenticator when you try to get the session
// Build session to create MimeMessage to send
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
props.setProperty("mail.smtp.quitwait", "false");
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("name_here", "password_here");
}
});

AuthenticationFailedException while sending email using Java

I'm trying to send email using java API and i'm giving the right emailid and password but still i get AuthenticationFailedException.
I also tried giving host=mail.smtp.port and changing port to 587 still i end up getting the same error..
Please help me where i'm going wrong..?
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "to#gmail.com";
// Sender's email ID needs to be mentioned
final String from = "from#gmail.com";
// Assuming you are sending email from localhost
final String host = "smtp.googlemail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.user", from);
//properties.setProperty("mail.smtp.password", "xyz");
properties.setProperty("mail.debug", "false");
properties.setProperty("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.port", "587");
// Get the default Session object.
// Session session = Session.getDefaultInstance(properties);
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "xyz");
}
});
session.setDebug(true);
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);
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Error:
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
Just check if you have enabled logging in from "Less Secure Apps" using this link. This setting needs to be enabled for the account from#gmail.com.

Error while sending mails using smtp

I need to send mail from my gmail account to another. I used the following code.
String fromaddress = "xxx#gmail.com";
String password = "yyy";
String hostname = "smtp.gmail.com";
String hoststring = "mail.smtp.host";
String toaddress = "yyy#gmail.com";
String emailcontent;
Properties properties = System.getProperties();
properties.setProperty(hoststring, hostname);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromaddress));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
message.setSubject("hi");
emailcontent = "hi...";
message.setText(emailcontent);
System.out.println(emailcontent);
Transport.send(message);
System.out.println("Sent....");
}catch (MessagingException mex)
{
mex.printStackTrace();
}
But i get the error as follows...
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25
How am i to solve this. Can you please help me out.
public static void sendEmail(Email mail) {
String host = "smtp.gmail.com";
String from = "YOUR_GMAIL_ID";
String pass = "YOUR_GMAIL_PASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
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");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set sender
message.setFrom(new InternetAddress("Senders_EMail_Id"));
// Set recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));
// Set Subject: header field
message.setSubject("SUBJECT");
// set content and define type
message.setContent("CONTENT", "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mex) {
System.out.println(mex.getLocalizedMessage());
}
}
}`
I think this should do the trick.
I think you need to change the port no. 25 to 587
you can get help from
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
gmail setting help link:
http://gmailsmtpsettings.com/
Just adding few more tweaks to the question above:
Change the port to 465 to enable ssl sending.
I don't think above code will work, as you need to have an authenticator object too. As smtp also requires authentication in case of gmail.
You can do something like:
Have a boolean flag,
boolean authEnable = true; //True for gmail
boolean useSSL = true; //For gmail
//Getters and setters for the same
if (isUseSSL()) {
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
}
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com", "xyz"));
}
};
if (isAuthEnable()) {
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}

Categories