I am creating an application where I need to send an email from custom gmail domain.
Here is my code for the same.
import java.time.LocalDateTime;
import java.util.Properties;
import java.util.Random;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class OTPMail {
static char[] OTP(int len)
{
System.out.println("Generating OTP using random() : ");
// Using numeric values
String numbers = "0123456789";
// Using random method
Random rndm_method = new Random();
char[] otp = new char[len];
for (int i = 0; i < len; i++)
{
// Use of charAt() method : to get character value
// Use of nextInt() as it is scanning the value as int
otp[i] =
numbers.charAt(rndm_method.nextInt(numbers.length()));
}
return otp;
}
public static void main(String[] args)
{
int length = 4;
char[] OTP = OTP(length);
System.out.print("Generated OTP is: ");
System.out.println(OTP);
String OTPString = String.valueOf(OTP);
//send an email
String messageForMail = "Your OTP for <company name>is: " + OTPString;
//update admin mail and password here
final String username = "shop#<ownDomain>.com";
final String password = "<passowrd>";
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("Kisna"));
//update recipient mail id here.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mailId>#gmail.com"));
message.setSubject("OTP");
message.setText(messageForMail);
Transport.send(message);
System.out.println("OTP sent to mail");
//check the time when mail is sent
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
It gives me error like:
Exception in thread "main" java.lang.RuntimeException:
javax.mail.AuthenticationFailedException: 534-5.7.14
Please
log in via 534-5.7.14 your web browser and then try again. 534-5.7.14
Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754
80-v6sm5667641ywh.55 - gsmtp
at OTPMail.main(OTPMail.java:81) Caused by:
javax.mail.AuthenticationFailedException: 534-5.7.14
Please
log in via 534-5.7.14 your web browser and then try again. 534-5.7.14
Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754
80-v6sm5667641ywh.55 - gsmtp
at
com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
at
com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
at javax.mail.Service.connect(Service.java:317) at
javax.mail.Service.connect(Service.java:176) at
javax.mail.Service.connect(Service.java:125) at
javax.mail.Transport.send0(Transport.java:194) at
javax.mail.Transport.send(Transport.java:124) at
OTPMail.main(OTPMail.java:75)
When I use same code for 'xxx#gmail.com' mails, it works fine.
But when I put custom domain like 'xxx#ownDomain.com' it gives me mentioned error. Any idea on how I can solve the same?
To send emails with Java Mail you need to let less secure apps access your account.
Go to Google Account -> Sign-in & security page and check Allow less secure apps then try again.
Related
I'm developing a basic email sender app that sends emails only to Gmail. After some time i figured out the hole scheme of the OAuth2 that Google now requires for authentication using the getToken() method from the GoogleAuthUtil API.
I've searched on the web for the JavaMail code to send the email using the token that i retrieve from the API and i found the following code that i'm using now:
package com.provider;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Provider;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import android.util.Log;
import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;
public class GMailOauthSender {
private Session session;
private String mailhost = "smtp.gmail.com";
private int port = 587;
private String user;
private String password;
public SMTPTransport connectToSmtp(String host, int port, String userEmail,
String oauthToken, boolean debug) throws Exception {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.imap.auth.login.disable", "true");
props.put("mail.imap.auth.plain.disable", "true");
session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = null;
transport.connect(host, port, userEmail, emptyPassword);
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", userEmail,
oauthToken).getBytes();
response = BASE64EncoderStream.encode(response);
transport.issueCommand("AUTH XOAUTH2 " + new String(response),
235);
return transport;
}
public synchronized void sendMail(String subject, String body, String user,
String oauthToken, String recipients) {
try {
SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com",
587,
user,
oauthToken,
true);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(user));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
smtpTransport.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
//Log.d("test", e.getMessage());
}
}
Unfortunately, the code simply does not work. I've been sticked with this for more than three weeks and nothing so far. Any suggestions?
It was real pain when I did this first time and to make it work..Follow these steps
First you need to setup OAuth2 for your app in developer console, go to this link for details
Now you need to add these 4 files, these will help to send mail in background. When users open the app users will be shown a consent screen(Code in file AUthActivity.java) and will have to allow the app to use gmail, this is one time activity and not required later. When doing this user is requesting a token from google servers and will be saved in preferences so that users is not asked again(AuthPreferences.java). After user approves it you can send mail using:
GMailSender gMailSender = new GMailSender();
gMailSender.sendMail("hi", "hi", authPreferences.getUser(), authPreferences.getToken(), "somemailid#gmail.com");
Link for the files in github: https://gist.github.com/ranjithnair02/1c6dab7dec51971abfec
You also need to add the below jar files to your project:
http://javamail-android.googlecode.com/files/mail.jar
http://javamail-android.googlecode.com/files/activation.jar
http://javamail-android.googlecode.com/files/additionnal.jar
You also need to add the following in Androidmanifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
This piece of code is picked up from http://www.tutorialspoint.com/javamail_api/javamail_api_sending_simple_email.htm
//package com.tutorialspoint;
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) {
// Recipient's email ID needs to be mentioned.
String to = "ABC#gmail.com";
// Sender's email ID needs to be mentioned
String from = "PQR#gmail.com";
final String username = "NAME";
final String password = "****";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
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", "25");
// 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);
}
}
}
I tried getting hint from this link. But it seems to be using a slightly different method.
On running it with a debugger, exception seems to be coming from following code:
Transport.send(message);
Following is the stack trace:
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.main(SendEmail.java:58)
PS: I have checked the username and password. Also, 2 step sign in process is not enabled for the account from which I am trying to send mail.
Can someone please explain what could be the cause of authenticatio failure? Alternatively, if there is some other post which has already answered the query, please point me to it. Thanks.
The server isn't happy with the username or password you're using. You can probably guess the common reasons that might be the case, staring with you provided the wrong username or password.
The JavaMail Session debugging output might provide more information.
change String host = "relay.jangosmtp.net";
to String host = "smtp.gmail.com";
and Port from 25 to 587
I want to send a mail using Gmail's SMTP server. Can you tell me why it won't connect to server when I run the bellow code.
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class SendTrick {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "465");
props.put("mail.from", "example#gmail.com");
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"ex#gmail.com");
msg.setSubject("JavaMail hello world example");
msg.setText("Hello, world!\n");
Transport.send(msg);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}
The exception in the log is
send failed, exception: javax.mail.MessagingException: Could not
connect to SMTP host: smtp.gmail.com, port: 25; nested exception is:
java.net.ConnectException: Connection refused: connect
You are not setting a mail.smtp.port since there is a duplication typo on the property mail.smtp.host, therefore the default port 25 is being used, as detailed in the the Exception.
GMail's SMTP is not running on port 25, which is why the connection is being refused. From Set up POP in mail clients, it looks like it should be 465 or 587, so you have a valid value but the property key is incorrect.
Edit:
You need use the correct property key for the port:
props.put("mail.smtp.port", "465"); // <-- use the word "port", not "host"
After this is fixed, you may also find authentication issues, as already noted in the comments, unless you have purposely left out the javax.mail.Authenticator code in the question.
Edit 2:
As I mentioned, you might need to specify additional properties to successfully authenticate and be authorised with the SMTP server, for example:
props.put("mail.smtp.starttls.enable", "true");
But, since you are using port 465 for SSL connection you will also need to specify additional SSL properties such as the mail.smtp.socketFactory.class.
Follow this steps:
Disable "Two factor authentication" in Your Email
Navigate to: "https://myaccount.google.com/lesssecureapps?pli=1" and turn on "Access for less secure apps"
Download JavaMail API "https://www.oracle.com/technetwork/java/javamail/index-138643.html" and Add it to your library
CODE
import java.util.Properties;
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 email_try {
public static void main(String ap[]) {
String myEmail = "YOUR EMAIL";
String password = "YOUR PASSWORD";
String opponentEmail = "THEIR EMAIL";
Properties pro = new Properties();
pro.put("mail.smtp.host", "smtp.gmail.com");
pro.put("mail.smtp.starttls.enable", "true");
pro.put("mail.smtp.auth", "true");
pro.put("mail.smtp.port", "587");
Session ss = Session.getInstance(pro, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myEmail, password);
}
});
try {
Message msg = new MimeMessage(ss);
msg.setFrom(new InternetAddress(myEmail));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(opponentEmail));
msg.setSubject("Your Wish");
msg.setText("java email app");
Transport trans = ss.getTransport("smtp");
Transport.send(msg);
System.out.println("message sent");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
TRY THIS CODE AND PUT CORRECT EMAIL ID AND PASSWORD
I am using a program to send emails. The code works when I use some other mail server. but I need to use my company's email account to send email. And the email account is provided by gmail xxxx#companyname.com. When I change the mail host to `stmp.gmail.com, I encounter the following error:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. st6sm11092256pbc.58
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1515)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1054)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:634)
at javax.mail.Transport.send0(Transport.java:189)
at javax.mail.Transport.send(Transport.java:118)
at Mail.sendMail(Mail.java:48)
at Test.main(Test.java:6)
The code is as follows
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class Email_Autherticator extends Authenticator {
String username = "xxxx#gmail";
String password = "xxxxx";
public Email_Autherticator() {
super();
}
public Email_Autherticator(String user,String pwd){
super();
username = user;
password = pwd;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
private String host = "smtp.gmail.com";
private String mail_head_name = "this is head of this mail";
private String mail_head_value = "this is head of this mail";
private String mail_to = "xxxx#gmail.com";
private String mail_from = "xxxx#Comanyname.com";//using gmail server
private String mail_subject = "this is the subject of this test mail";
private String mail_body = "this is mail_body of this test mail";
private String personalName = "xxx";
public void sendMail() throws SendFailedException{
try {
Properties props = new Properties();
Authenticator auth = new Email_Autherticator();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
System.out.println(props);
Session session = Session.getDefaultInstance(props,auth);
MimeMessage message = new MimeMessage(session);
message.setContent("Hello","text/plain");
message.setSubject(mail_subject);
message.setText(mail_body);
message.setHeader(mail_head_name, mail_head_value);
message.setSentDate(new Date());
Address address = new InternetAddress(mail_from,personalName);
message.setFrom(address);
Address toaddress = new InternetAddress(mail_to);
message.addRecipient(Message.RecipientType.TO,toaddress);
System.out.println(message);
Transport.send(message);
System.out.println("Send Mail Ok!");
} catch (Exception e) {
e.printStackTrace();
}
//return flag;
}
}
You almost certainly just need to rework your code to add the properties defined in the JavaMail API - Sending email via Gmail SMTP example example.
You can probably get away with setting your props to this:
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.user", gmailUsername);
properties.setProperty("mail.smtp.password", gmailPassword);
As this seems to be for work--if you can--I suggest using Spring. It makes it a lot cleaner and easier to use. I just recently did something similar to this with Spring and Gmail SMTP.
You need to define below properties in your java code.
import below package
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
and add following to your code:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Use javax.mail.authenticator to authenticate with gmail servers
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Try this should work for you.
If still having issues, refer this error doc:
https://pepipost.com/tutorials/common-javamail-smtp-errors/
for sending SMTP email using javaMail API
I am trying to write a simple Java program to send emails from my hotmail account using JavaMail API. Here is my code :
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 HotMailSend {
public static void main(String args[])
{
final String username = HOTMAIL.username;
final String password = HOTMAIL.password;
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.host", "smtp.live.com");
props.setProperty("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(HOTMAIL.username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(GMAIL.username));
message.setSubject("Testing Subject");
message.setText("Hey Buddy..!!!,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
And here is the error I am getting :
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Connection closed by remote host
at HotMailSend.main(HotMailSend.java:45)
Caused by: javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
java.net.SocketException: Connection closed by remote host
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2163)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2150)
at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1220)
at javax.mail.Transport.send0(Transport.java:197)
at javax.mail.Transport.send(Transport.java:124)
at HotMailSend.main(HotMailSend.java:40)
Caused by: java.net.SocketException: Connection closed by remote host
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1307)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:43)
at com.sun.mail.util.TraceOutputStream.write(TraceOutputStream.java:114)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2161)
... 5 more
I've used SMTP/Javamail with Hotmail before, so it definitely works. Were you sending a lot of emails in a short time? (I think they may block your mail or send it to the junk folder when you do that as a spam prevention measure.)
Check the e-mail that you're currently using if it arrived some message from microsoft.
With me occurred this problem, and when i looked for it, I had one e-mail that had the following subject: Verify your account to do more with Outlook.com.
They asked me to confirm that i'm really a human so I could continue to send automatic messages. They sent me a message to my cellphone and I managed to keep sending e-mails with Java Mail.