How should I send an mail using JavaMail and AWS - jakarta-mail

Hello everyone i am trying to send an email using JavaMail and Amazon SES, this is the code I have written,
static Properties props = new Properties();
static {
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", "userName");
props.setProperty("mail.aws.password", "secretKey");
}
void doThis() throws AddressException, MessagingException {
Session session = Session.getDefaultInstance(props);
Message mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("support#xyz.com"));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse("kaustubh#xyz.com"));
mimeMessage.setSubject("Subject");
mimeMessage.setContent("Message contenet", "text/html");
Transport t = new AWSJavaMailTransport(session, null);
t.connect();
t.sendMessage(mimeMessage, null);
t.close();
}
but i am getting an exception saying,
Exception in thread "main" javax.mail.SendFailedException: Unable to send email;
nested exception is:
com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
And I am not getting any solution for this, any suggestions from the stackOverflow family would be a great help.

Here is V2 SES code that sends email...
public class SendMessage {
// This value is set as an input parameter
private static String SENDER = "";
// This value is set as an input parameter
private static String RECIPIENT = "";
// This value is set as an input parameter
private static String SUBJECT = "";
// The email body for recipients with non-HTML email clients
private static String BODY_TEXT = "Hello,\r\n" + "Here is a list of customers to contact.";
// The HTML body of the email
private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
+ "<p>Here is a list of customers to contact.</p>" + "</body>" + "</html>";
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Please specify a sender email address, a recipient email address, and a subject line");
System.exit(1);
}
// snippet-start:[ses.java2.sendmessage.main]
SENDER = args[0];
RECIPIENT = args[1];
SUBJECT = args[2];
try {
send();
} catch (IOException | MessagingException e) {
e.getStackTrace();
}
}
public static void send() throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Add subject, from and to lines
message.setSubject(SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
// Create a multipart/alternative child container
MimeMultipart msgBody = new MimeMultipart("alternative");
// Create a wrapper for the HTML and text parts
MimeBodyPart wrap = new MimeBodyPart();
// Define the text part
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
// Define the HTML part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object
wrap.setContent(msgBody);
// Create a multipart/mixed parent container
MimeMultipart msg = new MimeMultipart("mixed");
// Add the parent container to the message
message.setContent(msg);
// Add the multipart/alternative part to the message
msg.addBodyPart(wrap);
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder()
.data(data)
.build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
.rawMessage(rawMessage)
.build();
client.sendRawEmail(rawEmailRequest);
} catch (SdkException e) {
e.getStackTrace();
}
// snippet-end:[ses.java2.sendmessage.main]
}
}
// snippet-end:[ses.java2.sendmessage.complete]

Exception in thread "main" javax.mail.SendFailedException: Unable to send email; nested exception is: com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
Amazon is telling you that you must verify the email address you're sending from or to. If the email address from and to are not verified the send email fails.

Related

Sending a Yahoo Email with JavaMail API

I am trying to send an email to a yahoo email account with this code.
However, I get this message:
javax.mail.MessagingException: Could not connect to SMTP host: winmo.smtp.mail.yahoo.com, port: 465, response: -1
I dont know what is wrong. I am new to java.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String to = "myemail#yahoo.com";
System.out.println("Type the subject of the email");
String subject = s.nextLine();
System.out.println("Type the content of the message");
String body = s.nextLine();
String from = "web#gmail.com";
String host = "winmo.smtp.mail.yahoo.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("sent");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

sending mail using javamail getting authentication issue

When I tried to send mail using following code, I got authentication issues.
Here's my code:
public class NewSendMail {
String to = "********";
String subject = "subject";
String msg ="email text....";
final String from ="*******";
final String password ="******";
public NewSendMail(){
}
public boolean sendMymail(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
// Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
Transport transport;
InternetAddress addressFrom = null;
try {
transport = session.getTransport();
addressFrom = new InternetAddress(from);
MimeMessage message = new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(msg, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
transport.connect();
Transport.send(message);
transport.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
It is throwing a javax.mail.AuthenticationFailedException.
How can I fix the issue?
The following code may help you
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
This code worked for me, If it is not working for you, Check your jar files
I tell everyone who asks for JavaMail help the same things. (I wonder why they call it a FAQ?)
Fix these common mistakes.
Follow this example for Gmail.
Turn on session debugging to get more details of what's going wrong, and post the output if you still can't figure it out.
Either you're sending the wrong username or password, or the server is rejecting your login attempt for other reasons, perhaps because you haven't enabled less secure apps.

How to write the body part while sending an email?

While sending the email after the script completed i am not able to add any body part. I want to add body like,
Hi xyz,
Please find the attached the reports attached.
With Best Regards,
Abc.
I am using the below code for sending the email . Can anyone please guide me how to send email.
package util;
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
public static void zipAndSendReport()
{
TestUtil.zip(System.getProperty("user.dir") +"\\HtmlReports");
String[] to={"xyz#xyz.com"};
String[] cc={"xyzff#xyz.com","xyzaa#xyz.com"};
String[] bcc={"xyzrwer#xyz.com"};
//This is for google
SendMail.sendMail("acv.ddg#gmail.com",
"070122dasdad3183",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Automation test Reports",
"Please find the reports attached.\n\n Regards\nWebMaster",
System.getProperty("user.dir")+"\\Reports.zip",
"Reports.zip");
}
public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
// props.put("mail.smtps.auth", "true");
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
//Session session = Session.getDefaultInstance(props, null);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("acv.ddg#gmail.com","070122sd3183"); }
});
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
//attachment start
// create the message part
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
// attachment ends
// Put parts in message
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
Please let us know will this code work or is there any better way of doing this?
Thanks,
Sudhansu
Your MimeMessage can either have text set via setText() or a multipart-body.
Since your use atteachments you have to use multipart. To add some plain text to the message create another MimeBodyPart and add it as the first to your Multipart:
....
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text);
mmp.addBodyPart(textPart);
MimeBodyPart messageBodyPart = new MimeBodyPart();
....

Java Mail: Getting Bounced Messages To Go To An Address Different From The Sender

I'm trying to get Java mail to send bounced email to a different address than the sender's address and not send the bounce message to the sender at all.
So far I can't do either in a test program ( below ).
The sender is "joe#acme.com".
I want bounce messages to go and only go to "bounce#acme.com"
I'm trying setting both the reply-to address and the Return-Path: header, but the bounces do not go to bounce#acme.com, only to joe#acme.com
When looking at the header of the bounce message the Return-Path: header is getting set to the sender, joe#acme.com, not to bounce#acme.com the way I want it to be.
I'm using javamail 1.4
Thanks in advance for any help or tips
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception{
String smtpServer = "msg.abc.acme.cp,";
int port = 25;
String userid = "authorized.person";
String password = "password";
String contentType = "text/html";
String subject = "test: bounce an email to a different address from the sender";
String from = "joe#acme.com";
String to = "bogus#fauxmail.com";
String replyto = "bounce#acme.com";
String body = "Test: get message to bounce to a separate email address";
InternetAddress[] arrayReplyTo = new InternetAddress[1];
arrayReplyTo[0] = new InternetAddress(replyto);
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
Session mailSession = Session.getInstance(props);
// Get runtime more runtime output when attempting to send an email
//mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.setReplyTo(arrayReplyTo);
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body,contentType);
message.setHeader("Return-Path:","<bounce#acme.com>");
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}// end class SendEmail
You need to set the "envelope from" address. See the javadocs for the com.sun.mail.smtp package for the property you can use to set it, or use the SMTPMessage class to set it.
And then hope that the mail server bouncing the message does the right thing and follows the spec...
This stackoverflow post explains that you need to set the sender's from using MimeMessage.addFrom() and that you need to set the "mail.smtp.host"
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception{
String smtpServer = "msg.abc.acme.cp,";
int port = 25;
String userid = "authorized.person";
String password = "password";
String contentType = "text/html";
String subject = "test: bounce an email to a different address from the sender";
String from = "joe#acme.com";
String to = "bogus#fauxmail.com";
String bounceAddr = "bounce#acme.com";
String body = "Test: get message to bounce to a separate email address";
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.from", bounceAddr);
Session mailSession = Session.getInstance(props);
// Get runtime more runtime output when attempting to send an email
//mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
//message.setFrom(new InternetAddress(from));
message.addFrom(InternetAddress.parse(from));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body,contentType);
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}// end class SendEmail

Could some one please let me know why could we get the following exception

javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
my code:
public class SendMail implements ActionListener
{
public void actionPerformed(ActionEvent e1)
{
String TO = textTo.getText();
Component Mail=sendMail;
if((TO.trim().length() < 1))
{
JOptionPane.showMessageDialog(Mail,
"Please enter some address to send mail",
"No Address to send mail", JOptionPane.ERROR_MESSAGE);
}
else{
String host = "smtp.gmail.com";//host name
String from = "mymail#gmail.com";//sender id
String to = textTo.getText();//reciever id
String pass = "password";//sender's password
String fileAttachment = textAttFile.getText();//file name for attachment
//system properties
Properties prop = System.getProperties();
// Setup mail server properties
prop.put("mail.smtp.gmail", host);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.user", from);
prop.put("mail.smtp.password", pass);
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
//session
Session session = Session.getInstance(prop, null);
// Define message
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(textSub.getText());
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//message body
messageBodyPart.setText(body.getText());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
//send message to reciever
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
JOptionPane.showMessageDialog(sendMail,
"Mail Sent Successfully.",
"Mail Sent.", JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}}
}
This JavaMail FAQ entry might help:
When connecting to my mail server over SSL I get an exception like "unable to find valid certification path to requested target".

Resources