JavaMail: Could not connect to SMTP server - java

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.

Related

aws SES 535 Authentication Credentials Invalid

I am trying to send message from java using aws SES .I saw similar question but I tried all the answers from that.
Question link: Amazon SES 535 Authentication Credentials Invalid
I have domain in SES management and created there from SMTP setting new IAM user with SMTP credentials, tried to login but giving this Error message: 535 Authentication Credentials Invalid.
Here is code:
static final String FROM = "news#example"; //have verified email
static final String FROMNAME = "NAME";
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
static final String TO = "my#gmail.com";
// Replace smtp_username with your Amazon SES SMTP user name.
static final String SMTP_USERNAME = "AKIAQZG5ZQZURE****";
// Replace smtp_password with your Amazon SES SMTP password.
static final String SMTP_PASSWORD = "MNYYlLz5sBB%2FA8****";//even encoded
// The name of the Configuration Set to use for this message.
// If you comment out or remove this variable, you will also need to
// comment out or remove the header below.
// static final String CONFIGSET = "ConfigSet";
// Amazon SES SMTP host name. This example uses the US West (Oregon) region.
// See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
// for more information.
static final String HOST = "email-smtp.eu-west-1.amazonaws.com";
// The port you will connect to on the Amazon SES SMTP endpoint.
static final int PORT = 25;
static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
static final String BODY = String.join(
System.getProperty("line.separator"),
"<h1>Amazon SES SMTP Email Test</h1>",
"<p>This email was sent with Amazon SES using the ",
"<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
" for <a href='https://www.java.com'>Java</a>."
);
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);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "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,FROMNAME));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
msg.setSubject(SUBJECT);
msg.setContent(BODY,"text/html");
// Add a configuration set header. Comment or delete the
// next line if you are not using a configuration set
// msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET);
// Create a transport.
Transport transport = session.getTransport();
// Send the message.
try
{
System.out.println("Sending...");
// 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());
}
finally
{
// Close and terminate the connection.
transport.close();
}
}
Attached two pictures , first one is IAM permission policy and second is SES domain permission policy

javax.mail.AuthenticationFailedException: 535 5.7.3 Cannot send mail

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

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

Getting error while trying to run java mail api with aws smtp

I am using aws smtp for sending mail in java project but when I am running my java project I am getting exception. I copied this program from here http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-java.html
But after following same steps as given in this link I am getting this exception so please suggest me what should I do.
Here is my code..
public class AmazonSESSample {
static final String FROM = "ansh#artle.in"; // Replace with your "From" address. This address must be verified.
static final String TO = "amit0133#gmail.com"; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
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 = "My SMTP username"; // Replace with your SMTP username.
static final String SMTP_PASSWORD = " my SMTP password"; // Replace with your SMTP password.
// Amazon SES SMTP host name. This example uses the US West (Oregon) region.
static final String HOST = "email-smtp.us-west-2.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 = 587;
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) {
ex.printStackTrace();
System.out.println("The email was not sent.");
System.out.println("Error message: " + ex.getMessage());
}
finally
{
// Close and terminate the connection.
transport.close();
}
}
}
Here is Exception
Attempting to send an email through the Amazon SES SMTP interface...
The email was not sent.
Error message: null
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:264)
at javax.mail.Service.connect(Service.java:134)
at awssmtp.AmazonSESSample.main(AmazonSESSample.java:60)

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.

Categories