What would be the error of the email method? - java

The previous settings of port, authentication, and protocol are correct for you sending the email.
And as a result i get a message like the one in the image.
Without a message and without attachment, I just get the signature by default in the mail.
thanks;
#Autowired
public Session emailSession;
#Override
public JsonObject sendEmail(final JsonObject json) throws CommunicationsException {
final JsonObject response = new JsonObject();
final String receiver = (String) json.get(RECEIVER);
final String subject = (String) json.get(SUBJECT);
final String messageBody = (String) json.get(MESSAGE_BODY);
final String attachment = (String) json.get(ATTACHMENT);
try {
MimeMessage msg = new MimeMessage(emailSession);
msg.setFrom(new InternetAddress(MAIL_USER_FROM));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
msg.setSubject(subject);
Multipart emailContenido = new MimeMultipart();
// Text
MimeBodyPart textoBodyPart = new MimeBodyPart();
textoBodyPart.setText(messageBody);
// Att
MimeBodyPart adjunto = new MimeBodyPart();
adjunto.attachFile("C:/hola.txt");
// Parts email
emailContenido.addBodyPart(textoBodyPart);
emailContenido.addBodyPart(adjunto);
msg.setContent(emailContenido);
Transport.send(msg);
System.out.println("Message ok");
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}

Related

Java mail : attach html content along with an attachment

I'm trying to send a mail with an attachment and also along with a html content.
I know how to send the html content and the attachments separately but is it possible to send the both the html and as well as the attachment together?
Here's what I've tried :
public static void sendAttachment(final String to, final String cc, final String subject, final String text,
final byte[] attachment, final String fileName) {
if (null == to) {
return;
}
try {
Properties props = getProperties();
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_EMPRIS));
message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
if(null != cc)
message.addRecipient(RecipientType.CC, new InternetAddress(cc));
if (null != subject)
message.setSubject(subject);
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(text);
BodyPart messageBodyPart2 = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource(attachment, "application/x-any");
messageBodyPart2.setDataHandler(new DataHandler(ds));
messageBodyPart2.setFileName(fileName);
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(messageBodyPart1);
multiPart.addBodyPart(messageBodyPart2);
message.setContent(multiPart);
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
This one sends the attachment and the setText(text) as a plaintext. Can this be changed to a html content instead of a plaintext?
Would greatly appreciate your help and thanks a lot.
Just create another mimeBodyPart with html content and setContent(htmlContent, "text/html"). Add that after your plain text body part.
Use below method and set html content in body
message.setContent(body,"text/html");
Set DataHandler for messageBodyPart1
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(text);
messageBodyPart1.setDataHandler(new DataHandler(textHtml, "text/html;charset=utf-8"));// this is to handle html

Spring Boot Thymeleaf email template inline image

I'm trying to use an inline image in my thymeleaf template. Followed by this manual http://www.thymeleaf.org/doc/articles/springmail.html
For unknown reason image is not sent, i also didn't get any errors.
in template:
<img src="image_name.png" th:src="|cid:${imageResourceName}|"/>
sending email:
#Autowired
private JavaMailSender mailSender;
#Autowired
private SpringTemplateEngine templateEngine;
#Value(value = "classpath:templates/mails/listing/images/img11.png")
private Resource logoImageResource;
public boolean sendRichEmail(String receipient, EmailType emailType) {
EmailMessageConstructor emailMessageConstructor = new EmailMessageConstructor(emailType);
String recipientAddress = receipient;
String subject = emailMessageConstructor.getEmailTopic();
String from = "no-reply#xxx.com";
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
final Context ctx = new Context();
ctx.setVariable("name", "User1");
ctx.setVariable("dateNow", new Date());
ctx.setVariable("dateExpired", MyUtils.addDays(new Date(), 30));
final String htmlContent = this.templateEngine.process(emailMessageConstructor.getEmailTemplate(), ctx);
mimeMessage.setContent(htmlContent, "text/html");
// Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
try {
String imageResourceName = logoImageResource.getFilename();
String imageContentType = new MimetypesFileTypeMap().getContentType(logoImageResource.getFile());
final InputStreamSource imageSource = new ByteArrayResource(IOUtils.toByteArray(logoImageResource.getInputStream()));
helper.addInline(imageResourceName, imageSource, imageContentType);
} catch (IOException e) {
e.printStackTrace();
}
helper.setTo(new InternetAddress(recipientAddress));
helper.setSubject(subject);
try {
helper.setFrom(new InternetAddress(from, "xxx"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mailSender.send(mimeMessage);
} catch (MessagingException e) {
logger.error("Message creation exception: "+e.getMessage());
}
return true;
}
Want to use the image located in
/resources/templates/mails/listing/images/img11.png

GWT Java email - java.io.UnsupportedEncodingException: text/html

I am sending an email with html text and an attachment and getting the error:
java.io.UnsupportedEncodingException: text/html
The code is:
public void emailMessage(String emailSubject, String message, String emailaddress, String imagePath) {
//Send an email
try {
//Send an email
SimpleEmail email = new SimpleEmail();
email.setHostName("mail.org");
email.setSmtpPort(25); //No authentication required
email.setFrom("address.org");
email.addTo(emailaddress);
email.setSubject(emailSubject);
email.setCharset("utf-8");
// Set the email message text.
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(message, "text/html");
// Set the email attachment file
FileDataSource fileDataSource = new FileDataSource(imagePath);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
// Create Multipart E-Mail.
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
email.setContent(multipart);
//Send the email
email.send();
} catch (EmailException e) {
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Initially I was sending an email without an attachment which worked. Then I added the multipart for the attachment and the text/html is no longer valid.
Try
textPart.setText(text, "utf-8" );
or
htmlPart.setContent(html, "text/html; charset=utf-8" );
This worked for me with java >= 8:
MimeMessage msg = new MimeMessage(session)
msg.setContent(content, "text/html")
use setContent instead setText

How to send mails to multiple recipients through java mail api [duplicate]

This question already has answers here:
Send mail to multiple recipients in Java
(12 answers)
Closed 5 years ago.
Below is the java program which send a mail through java mail api now the issue is that I want to enter multiple addresses into mailTo field. In the below code, you can see there is single entry for mailTo that is avdq#abc.com. However, I want to pass multiple entries as avdq#abc.com, tvdq#abc.com, and pvdq#abc.com. Please advise how to achieve this.
public class abcMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdq#abc.com";
//String mailCc = "avdg#abc.com ";
String mailFrom = "avdg#abc.com";
String mailSubject = "sgdtetrtrr";
String mailText = "Test Mail for mail body ";
sendEmail(mailTo, mailFrom, mailSubject, mailText, mailSmtpHost ,mailSmtpPort );
}
public static void sendEmail(String to, String from, String subject, String text, String smtpHost , String mailSmtpPort) {
try {
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mailSmtpPort", mailSmtpPort);
//obtaining the session
Session emailSession = Session.getDefaultInstance(properties);
emailSession.setDebug(true);
//creating the message
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Address[] cc = new Address[] {
new InternetAddress("avdg#abc.com"),
new InternetAddress("sWER#gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
MimeBodyPart attachPart = new MimeBodyPart();
String filename = "c:\\abc.pdf";
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(filename);
multipart.addBodyPart(attachPart);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You just need to do the same thing as what you did for cc field
Address[] to = new Address[] {InternetAddress.parse("avdq#abc.com"),
InternetAddress.parse("tvdq#abc.com"),
InternetAddress.parse("pvdq#abc.com")};
message.addRecipients(Message.RecipientType.TO, to);
Try this
String cc = "avdg#abc.com;sWER#gmail.com";
StringTokenizer st = new StringTokenizer(cc,":");
while(st.hasMoreTokens()) {
emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse(st.nextToken(),false);
}

Example of sending an email with attachment via Amazon in Java

Does anyone have an example of sending an email, with an attachment, via Amazon SES (in Java)?
Maybe a little bit late, but you can use this code (you also need Java Mail):
public class MailSender
{
private Transport AWSTransport;
...
//Initialize transport
private void initAWSTransport() throws MessagingException
{
String keyID = <your key id>
String secretKey = <your secret key>
MailAWSCredentials credentials = new MailAWSCredentials();
credentials.setCredentials(keyID, secretKey);
AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
AWSsession = Session.getInstance(props);
AWStransport = new AWSJavaMailTransport(AWSsession, null);
AWStransport.connect();
}
public void sendEmail(byte[] attachment)
{
//mail properties
String senderAddress = <Sender address>;
String recipientAddress = <Recipient address>;
String subject = <Mail subject>;
String text = <Your text>;
String mimeTypeOfText = <MIME type of text part>;
String fileMimeType = <MIME type of your attachment>;
String fileName = <Name of attached file>;
initAWSTransport();
try
{
// Create new message
Message msg = new MimeMessage(AWSsession);
msg.setFrom(new InternetAddress(senderAddress));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
msg.setSubject(subject);
//Text part
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, mimeTypeOfText);
multipart.addBodyPart(messageBodyPart);
//Attachment part
if (attachment != null && attachment.length != 0)
{
messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachment,fileMimeType);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
//send message
msg.saveChanges();
AWSTransport.sendMessage(msg, null);
} catch (MessagingException e){...}
}
}
Maybe a little bit late too.
Alternative to send mail using Java Mail and Amazon Raw Mail Sender
public static void sendMail(String subject, String message, byte[] attachement, String fileName, String contentType, String from, String[] to) {
try {
// JavaMail representation of the message
Session s = Session.getInstance(new Properties(), null);
MimeMessage mimeMessage = new MimeMessage(s);
// Sender and recipient
mimeMessage.setFrom(new InternetAddress(from));
for (String toMail : to) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toMail));
}
// Subject
mimeMessage.setSubject(subject);
// Add a MIME part to the message
MimeMultipart mimeBodyPart = new MimeMultipart();
BodyPart part = new MimeBodyPart();
part.setContent(message, MediaType.TEXT_HTML);
mimeBodyPart.addBodyPart(part);
// Add a attachement to the message
part = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachement, contentType);
part.setDataHandler(new DataHandler(source));
part.setFileName(fileName);
mimeBodyPart.addBodyPart(part);
mimeMessage.setContent(mimeBodyPart);
// Create Raw message
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mimeMessage.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
// Credentials
String keyID = "";// <your key id>
String secretKey = "";// <your secret key>
AWSCredentials credentials = new BasicAWSCredentials(keyID, secretKey);
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
// Send Mail
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
rawEmailRequest.setDestinations(Arrays.asList(to));
rawEmailRequest.setSource(from);
client.sendRawEmail(rawEmailRequest);
} catch (IOException | MessagingException e) {
// your Exception
e.printStackTrace();
}
}
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html has an example that sends both html and text bodies (with an attachment, of course). FWIW, here is the conversion and reorganization of its Java code to Kotlin. The dependency is 'com.sun.mail:javax.mail:1.6.2'.
data class Attachment(val fileName: String, val contentType: String, val data: ByteArray)
fun sendEmailWithAttachment(from: String, to: List<String>, subject: String, htmlBody: String, textBody: String,
attachment: Attachment) {
try {
val textPart = MimeBodyPart().apply {
setContent(textBody, "text/plain; charset=UTF-8")
}
val htmlPart = MimeBodyPart().apply {
setContent(htmlBody, "text/html; charset=UTF-8")
}
// Create a multipart/alternative child container.
val childPart = MimeMultipart("alternative").apply {
// Add the text and HTML parts to the child container.
addBodyPart(textPart)
addBodyPart(htmlPart)
}
// Create a wrapper for the HTML and text parts.
val childWrapper = MimeBodyPart().apply {
setContent(childPart)
}
// Define the attachment
val dataSource = ByteArrayDataSource(attachment.data, attachment.contentType)
// val dataSource = FileDataSource(filePath) // if using file directly
val attPart = MimeBodyPart().apply {
dataHandler = DataHandler(dataSource)
fileName = attachment.fileName
}
// Create a multipart/mixed parent container.
val parentPart = MimeMultipart("mixed").apply {
// Add the multipart/alternative part to the message.
addBodyPart(childWrapper)
addBodyPart(attPart) // Add the attachment to the message.
}
// JavaMail representation of the message
val s = Session.getDefaultInstance(Properties())
val mimeMessage = MimeMessage(s).apply {
// Add subject, from and to lines
this.subject = subject
setFrom(InternetAddress(from))
to.forEach() {
addRecipient(javax.mail.Message.RecipientType.TO, InternetAddress(it))
}
// Add the parent container to the message.
setContent(parentPart)
}
// Create Raw message
val rawMessage = with(ByteArrayOutputStream()) {
mimeMessage.writeTo(this)
RawMessage(ByteBuffer.wrap(this.toByteArray()))
}
val rawEmailRequest = SendRawEmailRequest(rawMessage).apply {
source = from
setDestinations(to)
}
// Send Mail
val client = AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build()
client.sendRawEmail(rawEmailRequest)
println("Email with attachment sent to $to")
} catch (e: Exception) {
println(e)
}
}
Here is an updated, cleaned up version with logging and check for production.
public void sendEmail(String to, String subject, String body, String attachment, String mimeType, String fileName) {
if (to == null) return;
String environment = System.getProperty("ENVIRONMENT", System.getenv("ENVIRONMENT"));
String logMessage;
if (environment != null && environment.equals("production")) {
logMessage = "Sent email to " + to + ".";
} else {
to = "success#simulator.amazonses.com";
logMessage = "Email sent to success#simulator.amazonses.com because $ENVIRONMENT != 'production'";
}
// https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-raw-using-sdk.html
Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
try {
message.setSubject(subject, "UTF-8");
message.setFrom(new InternetAddress(FROM));
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
MimeMultipart msg = new MimeMultipart("mixed");
MimeBodyPart wrap = new MimeBodyPart();
MimeMultipart msgBody = new MimeMultipart("alternative");
MimeBodyPart textPart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
textPart.setContent(body, "text/plain; charset=UTF-8");
htmlPart.setContent(body,"text/html; charset=UTF-8");
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
wrap.setContent(msgBody);
msg.addBodyPart(wrap);
MimeBodyPart att = new MimeBodyPart();
att.setDataHandler(new DataHandler(attachment, mimeType));
att.setFileName(fileName);
// DataSource fds = new FileDataSource(attachment);
// att.setDataHandler(new DataHandler(fds));
// att.setFileName(fds.getName());
msg.addBodyPart(att);
message.setContent(msg);
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder
.standard().withRegion(Regions.US_EAST_1).build();
message.writeTo(System.out);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
// .withConfigurationSetName(CONFIGURATION_SET);
client.sendRawEmail(rawEmailRequest);
Logger.info(this.getClass(), "sendEmail()", logMessage);
} catch (Exception ex) {
Logger.info(this.getClass(), "sendEmail()", "The email was not sent. Error: " + ex.getMessage());
}
}
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-raw-using-sdk.html
You use a shared credentials file to pass your AWS access key ID and secret access key. As an alternative to using a shared credentials file, you can specify your AWS access key ID and secret access key by setting two environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively).

Categories