Error while sending mails using smtp - java

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

Related

Session in JavaMail

In the following Code in the session object (PasswordAuthentication ) what username and password we have to provide to send mail ? Sender's username password or receiver's credentials?
I am really confused , I am using java Mail to send mail
public void sendMail(String email,String token)
{
// Recipient's email ID needs to be mentioned.
String to = email;
// Sender's email ID needs to be mentioned
// Assuming you are sending email through relay.jangosmtp.net
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("Issme-Customer-Service"));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Email Verification Of issme Account");
message.setContent(
"<h2>Email Verification </h2>" +
"<h3> Please goto the following URL to verify your ISSME account\n </h3> " +
token , "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
You need to send the sender's credentials which gmail's SMTP server will authenticate and then it'll send the email.

Postfix returning Invalid Addresses; 454 <to#domain.com>: Relay access denied

I'm using a pre-configured Postfix server and interacting with it using JavaMail. I am trying to send email notifications to any external domain that may request it.
Here is the java method to send a test email:
public void TestEmail() {
String to = "to#domain.com";
String from = "noreply#hostdomain.com";
final String username = "user";
final String password = "password";
String host = "xxx.xxx.xxx.xxx";
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");
Session session = Session.getInstance(props,
new 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("Test Email");
message.setContent("This is a test email", "text/html");
Transport.send(message);
System.out.println("The test message was sent!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
When I run the method that contains the JavaMail code, I get
generalError: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 454 4.7.1 <to#domain.com>: Relay access denied
I was able to test outgoing mail from the Postfix server using
echo "This is the body" | mail -s "This is the subject" to#domain.com
and did receive the email in the testing inbox.
I'm not 100% sure what all the settings are on the Postfix server, but I am suspecting that is where the issue is, but I'm not familiar enough with it to start digging around and changing things all willy-nilly.
EDIT:
I removed the Authenticator() set up from the Session creation and replaced Transport.send() with recommended code block
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
The entire new set of code is:
String host = "xxx.xxx.xxx.xxx";
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");
Session session = Session.getInstance(props, null);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setContent("This is a test email", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("The test message was sent!");
} catch (MessagingException e) {
System.out.println("Error: " + e);
e.printStackTrace();
throw new RuntimeException(e);
}
}
This has changed the error message I am receiving to: Unrecognized SSL message, plaintext connection?
Solved
Solution: The Java code was not the issue. The Postfix server was not configured to accept emails originating from a non-local IP/host. The IPs were added to the main.cf in the mynetworks variable.
This article has more information.
First, get rid of the Authenticator as described in the JavaMail FAQ. That will ensure that it's really trying to authenticate to the server. Turn on JavaMail session debugging to make sure it is authenticating.
Note that you can replace
Transport transport = session.getTransport("smtp");
transport.connect(host, 587, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
with
Transport.send(message, username, password);
You can get rid of the mail.smtp.auth setting, but keep the other properties.
Make sure you're using the most current version of JavaMail.
If it still doesn't work, the article above may provide some clues as to how to change the Postfix configuration.

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

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

Categories