Not able to send Email using Amazon SES in Java - java

I am using below mentioned code to send Email.
public static void send(String email, String subject, String body) {
try {
fromEmail = "abc.#xyz.com";
Content subjectContent = new Content(subject);
Destination destination = new Destination().withToAddresses(new String[] { "cde#gmail.com" });
Content htmlContent = new Content().withData("<h1>Hello - I hope you're having a good day.</h1>");
Body msgBody = new Body().withHtml(htmlContent);
// Create a message with the specified subject and body.
Message message = new Message().withSubject(subjectContent).withBody(msgBody);
SendEmailRequest request = new SendEmailRequest()
.withSource(fromEmail)
.withDestination(destination)
.withMessage(message);
SendRawEmailRequest sendRawEmailRequest = new SendRawEmailRequest()
.withSource(fromEmail)
.withDestinations(destination.getBccAddresses())
.withRawMessage(new RawMessage());
AWSCredentials credentials = new BasicAWSCredentials(userName,password);
AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(credentials);
// ListVerifiedEmailAddressesResult verifiedEmails =
// sesClient.listVerifiedEmailAddresses();
SendRawEmailResult result = sesClient.sendRawEmail(sendRawEmailRequest);
System.out.println(result + "Email sent");
} catch (Exception e) {
logger.error("Caught a MessagingException, which means that there was a "
+ "problem sending your message to Amazon's E-mail Service check the "
+ "stack trace for more information.{}" + e.getMessage());
e.printStackTrace();
}
}
I am getting below mentioned error.
com.amazonaws.AmazonServiceException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/
host:email.us-east-1.amazonaws.com
user-agent:aws-sdk-java/1.9.0 Linux/3.19.0-25-generic Java_HotSpot(TM)_64-Bit_Server_VM/25.66-b17/1.8.0_66
x-amz-date:20160223T062544Z
host;user-agent;x-amz-date
4c1f25e3dcf887bd49756ddd01c5e923cf49f2affa73adfc7059d00140032edf'
(Service: AmazonSimpleEmailService; Status Code: 403; Error Code: SignatureDoesNotMatch;

This is a Sample code to send Email using Amazon SES.
Initially when you create an Amazon SES account, the account will be in Sandbox mode which allows you to send only 200 emails. For Switching this to production mode, you need to "Request" for expanding email limit. Please go through the documentation.
Pre requisites:
You need to have Amazon SES account activated.
verify email addressses (to and from) or domain if you are currently in Sandbox mode.
Under "SMTP settings" in Navigation bar, you can generate your SMTP credentials.
This will include a smtp username and password. You can download a csv file containing this details as well.
sending email using Java :
public class AmazonSESExample {
static final String FROM = "your from email address";
static final String FROMNAME = "From 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 = "receiver email address";
// Replace smtp_username with your Amazon SES SMTP user name.
static final String SMTP_USERNAME = "username generated under smtp settings";
// Replace smtp_password with your Amazon SES SMTP password.
static final String SMTP_PASSWORD = "password generated under smtp settings";
// 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.us-east-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");
// 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();
}
}
}

The credentials you are providing is incorrect. You are giving IAM username and password. Instead you have to provide the access_key_id and access_key_id.
AWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key)
See: Providing AWS Credentials in the AWS SDK for Java

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)

GAE not working for send mail using Send Grid using java

I'm trying to send a mail using SendGrid by deploying my code to GAE. Following is my code.
private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
private static final String SMTP_AUTH_USER = "*******";
private static final String SMTP_AUTH_PWD = "*******";
private static final int SMTP_PORT = 2525;
public void sendCustomer(String userName, String toEmail, int custId) {
try {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
Multipart multipart = new MimeMultipart("alternative");
// Sets up the contents of the email message
BodyPart part1 = new MimeBodyPart();
part1.setText("Hello "
+ userName
+ "\n\n\n\n"
+ "Welcome to NotionViz. You have been registered successfully in NotionViz.");
multipart.addBodyPart(part1);
message.setText("UTF-8", "html");
message.setContent(multipart);
message.setFrom(new InternetAddress(SMTP_AUTH_USER));
message.setSubject("Customer Registration");
InternetAddress internetAddress = null;
try {
internetAddress = new InternetAddress(toEmail);
internetAddress.validate();
} catch (Exception e) {
System.out.println("Not a valid email address");
}
message.addRecipient(Message.RecipientType.TO, internetAddress);
InternetAddress address = new InternetAddress("cloud.spaninfotech#gmail.com");
message.setFrom(address);
// Sends the email
transport.connect(SMTP_HOST_NAME, SMTP_PORT, SMTP_AUTH_USER,
SMTP_AUTH_PWD);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.sendMessage(message,
message.getFrom());
transport.close();
} catch (Exception e) {
}
}
// Authenticates to SendGrid
class SMTPAuthenticator extends javax.mail.Authenticator {
#Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
This program is working fine and sending mail in local. But if i deploy to GAE and check, I'm not getting an email. Please let me know why GAE restricting third party mail sending.
Try changing the port that you're using. You can hit SendGrid over port 587, 25 or 2525 for plain/TLS connections (465 if you were going to be using SSL).
SendGrid suggests port 587 to avoid rate limits set by some hosting companies so I would give that a shot.
On GAE sockets are a subject to a series of restrictions (see Sockets API documentation). Authenticated SMTP is allowed on submission port 587, so you can use it as already suggested by LaCroixed.

Categories