JavaMail exception : Could not connect to smtp host - java

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

Related

Javamail - sending from localhost instead of godaddy server

When I am trying to send a mail from "smtpout.asia.secureserver.net", it is sending from localhost instead of the "secureserver" host.Below is the code :
Properties props = new Properties();
props.put("mail.smtp.host","smtpout.asia.secureserver.net");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxx#xxxxx.net","xxxxx");
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(sub);
message.setText(msg);
//send message
Transport.send(message);
System.out.println("message sent successfully");
}
catch (MessagingException e) {throw new RuntimeException(e);}
Debug :
com.sun.mail.smtp.SMTPSendFailedException
550 <narasimhatejav#teja> Sender Rejected - MAILFROM must be a valid domain. Ensure the mailfrom domain: "teja" has a valid MX or A record.
DEBUG SMTP: got response code 550, with response: 550 <narasimhatejav#teja> Sender Rejected - MAILFROM must be a valid domain. Ensure the mailfrom domain: "teja" has a valid MX or A record.
But if i change the host to "smtp.gmail.com" it is working fine.
Change the Java mail Jar to v1.5+ and add void javax.mail.internet.MimeMessage.setFrom(String address) function
It's sending from localhost because you made most of the common JavaMail mistakes.
The MAILFROM problem is because the host name or name service is misconfigured on your machine. As a workaround you can set the mail.smtp.localhost property.

after sending few emails Could not connect to SMTP host , nested exception is: java.net.ConnectException: Connection refused: connect

I want to get all unread emails from server and send each message to another email. When I send each unread email (Using HostGator), after sending few mails (30-40) an error occurs as I mentioned. This is my sending method. What can i do? I checked with smtp port 25,465,587. but none of them worked. Same error appears. :/ if any one knows how to handle it please let me know. Thank you..
email send method:-
public static void send(String sub,final String user, final String pass, String toMails) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.host", "gator.hostgator.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipients(Message.RecipientType.TO, toMails);
message.setSubject(sub);
message.setText("-Body-");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("-Body-");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
}
This is error message :-

Error when sending mail in 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();
}
}
}

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;

This is the code I am using to send an email:
#Override
public void sendEmail(String from, String to, String subject, String content) {
//we set the credentials
final String username = ConfigService.mailUserName;
final String password = ConfigService.mailPassword;
//we set the email properties
Properties props = new Properties();
props.put("mail.smtp.host", ConfigService.mailHost);
props.put("mail.smtp.socketFactory.port", ConfigService.mailSmtpSocketPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", ConfigService.mailSmtpPort);
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));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
Transport.send(message);
LOG.info(" Email has been sent");
} catch (MessagingException e) {
LOG.error(" Email can not been sent");
e.printStackTrace();
}
}
When I run this I obtain the next error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
I have seen another question related to this one here, but there is no accepted answer on that question. I can ping to smtp.gmail.com and also I can access the gmail account with the credentials.
This is running in my machine.
Any idea what could be the problem?
I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.
See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014
It works for me.

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