javax.mail.AuthenticationFailedException: 535 5.7.3 Cannot send mail - java

I'm having trouble with error
javax.mail.AuthenticationFailedException: 535 5.7.3
Authentication when trying to send an email. I've tried using two different email accounts. One using Office365 server details and the other using Gmail server details.
In both cases I get the same error. My code is below. Outside of my code the email addresses can send and receive email successfully without issue. This is my email class as it is the part that isn't working. All other aspects of my program work. Any help you can provide is greatly appreciated.
public class SPUREMAIL{
//CONSTANTS - Things that will never change
private static final String HOST = "smtp.office365.com";
private static final String PORT = "587";
private static final String SENDER = "EMAIL";
private static final String PASSWORD = "PASSWORD";
private static final String SUBJECT = "Spur Design has shared a file with you";
private static final String MESSAGE = "This email message was sent from an unmonitored address. Please contact your Spur Design representative for any questions or concerns";
//this item will change, its the direct link to the file
private String URLToFile;
private String recipient;
public SPUREMAIL(String URLToFile, String recipient){
this.URLToFile = URLToFile;
this.recipient = recipient;
}
//Properties for email
private Properties getProperties(){
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", HOST);
properties.put("mail.smtp.port", PORT);
properties.put("mail.smtp.user", SENDER);
properties.put("mail.smtp.password", PASSWORD);
return properties;
}
//Creating an email session so I can authenticate to server
Session session = Session.getInstance(getProperties(), new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(SENDER, PASSWORD);
}
});
public void sendMail(){//This will actually attempt to send the email successfully
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(SUBJECT);
message.setText(MESSAGE);
Transport.getTransport("smtp");
Transport.connect(HOST, SENDER, PASSWORD, pass);
Transport.sendMessage(MESSAGE, message.getAllRecipients());
}
catch(MessagingException e){
System.out.println("send failed, exception: " + e);
}
System.out.println("Sent!!!!");
}
}

Few suggestion which you can try and check if they work for you.
If you are trying outlook, I am assuming you are trying to connect your internal organization email servers. Try with port 25 and check if setting mail.smtp.starttls.enable to false make a difference.
I don't think you need to use username and password. You can remove it in case of outlook. You will need that in case of gmail.
You might want white-list your ip address by the firewall team. They have to allow connection from your machine.
Try installing a local email server, I have used papercut and it works like a charm.
Before sending your email using gmail you have to allow non secure apps to access gmail you can do this by going to your gmail settings.
Good luck.

have you checked this link -
javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful
It says it could the mail server configuration issue for your organization where your email id is not allowed to send mail via code. May be your mail server administrator can help here.
Also, this link - https://confluence.atlassian.com/confkb/unable-to-send-email-due-to-javax-mail-authenticationfailedexception-error-message-151519398.html , says the cause could be the mail server configured incorrectly.

Sometimes a pretty change will make a huge response, this case is also like that. You have to give full mail address at username. Sender's mail id's username should be with #domain.com
username : ******_****#domain.com

The issue with my code was two-fold. One, the email class was not being compiled when I compiled the entirety of my project. This was causing my Transport calls to go unchecked. Changed the Transport calls to the bloc below and after manually compiling email class successfully I was able to send emails perfectly fine. All credit goes to Bill Shannon for pointing me in the right direction.
public void sendMail(){//This will actually attempt to send the email successfully
try{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(SUBJECT);
message.setText(MESSAGE);
Transport.send(message, message.getAllRecipients());
}
catch(MessagingException e){
System.out.println("send failed, exception: " + e);
}
System.out.println("Sent!!!!");
}
}

Related

How to deal with gmail App password using Javax Mail

My Java Windows app needs to send email and allow the user to specify his/her email account credentials: host, port, username, password. It works when I use my credentials for an account at my hosting service, but not so well when using a Gmail account, as my prospective users might want to do. The problem is Gmail insists on an "App password." So, I follow the Google instructions and create a 16-character App password which Google says has to be used one time only. However, I find that the App password MUST be used for subsequent runs.
Here's a sample program that demonstrates the problem. It will fail if I use that actual password for the Gmail account. It will work after I've created an App/device specific password (16 characters) and used it as the password, as it should. But, I have to use that 16-character password thereafter as well. What am I missing?
public class SendEmailTLS {
// Example 1 from https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
public static void main(String[] args) {
final String username = "me123#gmail.com";
final String password = "mypassword";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("me123#gmail.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("you456#hotmail.com")
);
message.setSubject("Testing Gmail TLS");
message.setText("Dear sir,"
+ "\n\n I'm testing TLS,using port 587");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
I want to add that I'm now suspecting that what I'm seeing is the way it's supposed to work. I had been thinking the 16-char App specific pw was a "Salt" kind of thing to protect the Gmail server. I have now read that it's really just an alternative password for my Gmail account. If anyone can confirm or deny this new perspective, I would be grateful.

java- How to use services for sending email?

I have a simple web application where different users can log into it. One of the important feature is user can access a document and send email of it's content to an outsider like third party. Below is just how the email looks like to give an idea:
It's pretty self explanatory and I can send to multiple user if I want like abc#example.com,efg#hotmail.com,... in the field box shown.With all this, I am using Java Mail API to make it work and after hitting the send button,it sends directly to the recipient.No issue at all.
Now, I want to modify this by doing this email feature as a service.What this means is when I send the email,the content and info filled in will be stored in a table in MYSQL and the service(running in background) will pick up from the table and do the sending.
This is my function:
public void sendEmail(String recipient, String subject, String content,
String host, String port, final String senderaddress,
final String password) {
try {
System.out.println("Please Wait, sending email...");
/*Setup mail server */
Properties props = new Properties();
props.put("mail.smtp.host", host); //SMTP Host
props.put("mail.smtp.port", port); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderaddress, password);
}
};
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(senderaddress));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(content);
try {
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Can this be done in the way I want because I am unsure how to make it work?
1 ) After hitting Sending mail button from UI, You need to call a method for saving data like recipient, subject, content in DB
2)Write an email sender Service which retrieves non_delivered / pending mail from DB table and send it through Java Mail API
3)Scheduled email sender service with the help of ScheduledExecutorService

554 message rejected email address is not verified. amazon ses-java

I have been verified both from and to email addresses(both the emails are case sensitive) over and over
and I still get the 554 Message rejected: Email address is not verified Rejection from SES. But when i try to send the emails from Amazon SES Console by using the same email, it is working fine. If my from and to emails not been verified then from console also it should nt work. Not able to understand what is going on.
public class AmazonSESSample {
static final String FROM = "from email";
static final String TO = "to email";
static final String BODY = "This email was sent through the Amazon SES SMTP interface by using Java.";
static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
// Supply your SMTP credentials below. Note that your SMTP credentials are different from your AWS credentials.
static final String SMTP_USERNAME = "SMTP USER NAME";
static final String SMTP_PASSWORD = "SMTP PWD";
static final String HOST = "email-smtp.us-east-1.amazonaws.com";
// Port we will connect to on the Amazon SES SMTP endpoint. We are choosing port 25 because we will use
// STARTTLS to encrypt the connection.
static final int PORT = 25;
public static void main(String[] args) throws Exception {
// Create a Properties object to contain connection configuration information.
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", PORT);
// Set properties indicating that we want to use STARTTLS to encrypt the connection.
// The SMTP session will begin on an unencrypted connection, and then the client
// will issue a STARTTLS command to upgrade to an encrypted connection.
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(FROM));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
msg.setSubject(SUBJECT);
msg.setContent(BODY,"text/plain");
// Create a transport.
Transport transport = session.getTransport();
// Send the message.
try
{
System.out.println("Attempting to send an email through the Amazon SES SMTP interface...");
// Connect to Amazon SES using the SMTP username and password you specified above.
transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("Email sent!");
}
catch (Exception ex) {
System.out.println("The email was not sent.");
System.out.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
finally
{
// Close and terminate the connection.
transport.close();
}
}
}
I had the same problem, and it turned out to be a simple blind copy-paste issue. Currently, there are 3 regions with SES. Depending on which region you setup the ID, the HOST variable has to be modified accordingly.
static final String HOST = "email-smtp.us-east-1.amazonaws.com";
That fixed my problem. Afterwards, if you want to send emails to unverified email addresses, you have to move your setup out of the sandbox.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html
Is this the first time you are using this account with SES? If so then you must be in sandbox mode
If your account is still in the sandbox, you also must verify every recipient email address except for the recipients provided by the Amazon SES mailbox simulator.
SES Doc
You can follow these steps :
1 Log into the AWS Management Console.
2 Go to SES Sending Limits Increase.
3 Fill in the required details and set the limit to your desired usage
Moving Out of Sandbox

Delivery Confirmation For Sent Mail

My requirement is to send E-Mail Alerts to various customers for our client for which, we're planning to use JavaMail API. However, once mail is sent, we need to update status in DB as Sent/Delivered/Failure depending on the status of the mail. Please tell me how do we get Delivery Notification for the mail reaching the Mail Server of the Receiver. It's not necessary to ensure whether the person has read the mail or not, however, it will be great if we'll be able to know that. The mandatory thing to check is for delivery. How can we get the status. What I read was that using 'SMTPMessage' we can get the status, however, I couldn't find a code sample for how to read the Notification. I am putting my code which is very sample of what I have done till now. Please let me know how I can achieve the thing which we are trying to fulfill.
public class MailSender {
private int port = 25;
private String host = "testmailsrvr";
private String from = "test#test.com";
private boolean auth = true;
private String username = "test";
private String password = "test#123";
private Protocol protocol = Protocol.SMTP;
private boolean debug = true;
public void sendEmail(String strMailID, String strSubject, String strBody) throws MessagingException{
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
case SMTP:
props.put("mail.smtp.ssl.enable", false);
break;
}
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private PasswordAuthentication pa = new PasswordAuthentication(username, password);
#Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = {new InternetAddress(strMailID)};
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject(strSubject);
message.setSentDate(new Date());
message.setText(strBody);
Transport.send(message);
}
}
You'll want to read these JavaMail FAQ entries:
If I send a message to a bad address, why don't I get a SendFailedException or TransportEvent indicating that the address is bad?
When a message can't be delivered, a failure message is returned. How can I detect these "bounced" messages?
Then read the javadocs for the com.sun.mail.smtp and com.sun.mail.dsn packages to learn about Delivery Status Notifications.
You will have to approach the issue differently. The Transport.send() method will throw a SendFailedException if it runs into problems sending to any of the recipients. The exception will give you information on which recipient addresses failed. You should catch that exception, get the failing addresses and record them.
You might want to look into http://www.ultrasmtp.com. This service will send a notice back to the recipient upon the message being accepted, deferred, or refused by the receiving mail server. There is also an option to setup alerts for opened messages.

JavaMail: Could not connect to SMTP server

The following code causes an error. Please help me understand what's wrong.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
public static void main(String [] args)throws MessagingException
{
SendMail sm=new SendMail();
sm.postMail(new String[]{"abc#yahoo.co.in"},"hi","hello","xyz#gmail.com");
}
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "webmail.emailmyname.com");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}
Exception:
<pre>
com.sun.mail.smtp.SMTPSendFailedException: 450 smtpout04.dca.untd.com Authentication required
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at javax.mail.Transport.send0(Transport.java:191)
at javax.mail.Transport.send(Transport.java:120)
at SendMail.postMail(SendMail.java:52)
at SendMail.main(SendMail.java:10)
The "Authentication required" in the exception message suggests that the target SMTP server requires you to log in (Perhaps via TLS or SSL). This wasn't common on SMTP servers until a few years ago (it's an anti-spam measure) so it's easy to overlook.
To authenticate with JavaMail:
To use SMTP authentication you'll need to set the mail.smtp.auth property (see below) or provide the SMTP Transport with a username and password when connecting to the SMTP server. You can do this using one of the following approaches:
Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback.
Note that the mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly.
This approach allows you to use the static Transport send method to send messages.
Call the Transport connect method explicitly with username and password arguments.
This approach requires you to explicitly manage a Transport object and use the Transport sendMessage method to send the message. The transport.java demo program demonstrates how to manage a Transport object. The following is roughly equivalent to the static Transport send method, but supplies the needed username and password:
Transport tr = session.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges(); // don't forget this
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
Note that many, many ISPs block access to external port 25 on servers outside of their network. Instead, the ISP forces you to use their SMTP server.
If you're getting "authentication required", you must first enter your user name and password and issue at least one request such as check for new mail. Even though SMTP does not require a username and password to SEND email, many SMTP servers still implement this by making you log in and check your mail via POP or IMAP before you can send any.

Categories