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
Related
I have looked at many postings on the ( I need to add the mail.jar and activation.jar to oracle Sql developer ):
"javax.mail.NoSuchProviderException:No provider for Address type: rfc822"...
I have written other classes in java that are used by Oracle Forms6i, but can't get this email portion to work. The code that seems to be failing is:
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 EnvoyerEmail {
private String username = "xxxxxxx#gmail.com";
private String password = "****";
public void envoyer() {
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("xxxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("yyyyyy#gmail.com"));
message.setSubject("Test email");
message.setText("Bonjour, ce message est un test ...");
Transport.send(message);
System.out.println("Message_envoye");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
EnvoyerEmail test = new EnvoyerEmail();
test.envoyer();
}
}
But I keep getting the error mentioned above when it tries to send it. I assure you that I have the mail.jar, activation.jar, pop3.jar, mailapi.jar, smtp.jar, imap.jar in the class path. So that is not the problem.
I was suggested on an Oracle Forum that this will need to be signed. I'm very ignorant of this (the java experience that I have is with JSP), but thought that I got things "secured/signed", but I still keep getting the same problem.
Can someone tells me why the app throws this?
W/System.err: javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:319)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at javax.mail.Transport.send0(Transport.java:188)
W/System.err: at javax.mail.Transport.send(Transport.java:118)
at com.example.**.Utils.SendMail.doInBackground(SendMail.java:71)
at com.example.**.Utils.SendMail.doInBackground(SendMail.java:19)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
I'm trying to send a mail with javamail api.
I want to mention that I checked on the mail account, less secure apps.
This is the SendMail class
package com.example.****.Utils;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
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 SendMail extends AsyncTask<Void, Void, Void> {
private Context context;
private Session session;
private String email;
private String subject;
private String message;
public SendMail(Context context, String email, String subject, String message)
{
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Sending mail...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
Toast.makeText(context, "Message Sent", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... params) {
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.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Config.EMAIL, Config.PASSWORD);
}
});
try {
MimeMessage mm = new MimeMessage(session);
mm.setFrom(new InternetAddress(Config.EMAIL));
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
mm.setSubject(subject);
mm.setText(message);
Transport.send(mm);
}
catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
And here I'm using it
String email = "******";
String subject = "Activation";
String message = "This User requires activation: " + " Click here ";
SendMail sm = new SendMail(this, email, subject,message);
sm.execute();
I provided the right password, I checked that on my Google Account, it should be working
can you please help me?
Thank you in advance!
There is a property missing in your implementation.
Use props.put("mail.smtp.ssl.trust", "smtp.gmail.com"); in your doInBackground() method to overcome this issue.
Explanation:
Gmail requires SSL
From java mail documentation:
The following code fragment shows a simple way to incorporate the needed configuration in your application:
String host = "smtp.gmail.com";
String username = "user";
String password = "passwd";
Properties props = new Properties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.ssl.enable", "true");
// set any other needed mail.smtp.* properties here
Session session = Session.getInstance(props);
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport.send(msg, username, password);
Final Solution After losing many days I found this solution. you should enable Two-Factor Authentication in your Gmail account and then create App Password by fellow these steps:
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
2-Step Verification is not set up for your account.
2-Step Verification is only set up for security keys.
Your account is through work, school, or other organizations.
You turned on Advanced Protection.
At the bottom, choose Select app and choose the app you using and then Select the device and choose the device you’re using, and then Generate.
Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
after that copy the generated password and paste it into your JavaMail password section.
Good luck.
I have a program that I can send emails through. However, this needs to be a part of a much bigger program. The Email class is under a different package whereas my other 2 classes (The driver class/main program, as well as another object class) are both in the default package. Can I access the email class despite it being in a different package or do I need them all to be in one package? And how do I go about doing either of these? Currently, I tried removing the main method part of the email class and putting it in the default package with my driver class, this resulted in many syntax errors. Below are some photos showing my classes and some code. The SendMail class is the same as SendMailTLS just with the main method being removed and put into the default package. The SendMailTLS class works perfectly, I just need to be able to access it from the IA class.
SendMail Class:
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 SendMail {
final String username = "treybyroncollier#gmail.com";
final String password = "13october";
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("treybyroncollier#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("treycollier#live.co.uk"));
message.setSubject("THIS EMAIL IS A TEST");
message.setText("Hello Trey, just to let you know that this email is a test and everything is working with Java.");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
SendMailTLS Class:
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 SendMailTLS {
public static void main(String[] args) {
final String username = "treybyroncollier#gmail.com";
final String password = "13october";
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("treybyroncollier#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("treycollier#live.co.uk"));
message.setSubject("THIS EMAIL IS A TEST");
message.setText("Hello Trey, just to let you know that this email is a test and everything is working with Java.");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You should learn the basics first and then start with such a comlicated program.
In your sendMail class, you added all of your code directly into the class body, that's not going to work. Instead, create a method in that class and paste your code in there.
Then you can call that method from your other class after you imported the package.
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 SendMail {
public static void start() {
final String username = "treybyroncollier#gmail.com";
final String password = "13october";
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("treybyroncollier#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("treycollier#live.co.uk"));
message.setSubject("THIS EMAIL IS A TEST");
message.setText("Hello Trey, just to let you know that this email is a test and everything is working with Java.");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You can then run that code from your new main method or any other method you like.
public class YourMainClass {
public static void main(String[] args) {
SendMail.start();
}
}
In short, if you don't want your main method to execute when you start the program, just change its name from main to something of your choice and remove the parameter String[] args.
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