Making attachement as password protected through java itself - java

I have developed a java mail api program which will send the mail and it also attaches the pdf file , so finally a mail is delivered in which pdf file is attached .
now can you please advise i want to make that pdf file as password protected through my java program itself for example i want to modify my below program such as that for opening an pdf file password 1234 is created and whenever an mail is sent the client should open the pdf file but before opening he should enter 1234 in the pop up box of pdf file to see it , can you please advise how can i achieve this in java program itself please. Thanks in advance below is my java program
public class BrokMailTest {
public static void main(String[] args) {
String mailSmtpHost = "77.77.77.77";
String mailSmtpPort = "4321" ;
String mailTo = "avdg#abc.com";
//String mailCc = "avdg#abc.com ";
String mailFrom = "avdg#abc.com";
String mailSubject = "*****%%%%%%%%*********Email POC Brokerage for Rel 14.0****%%%%%%%%********";
String mailText = "Test Mail for Brokerage POC";
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);
Message emailMessage = new MimeMessage(emailSession);
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//emailMessage.addRecipients(Message.RecipientType.CC, InternetAddress.parse("avdg#abc.com"));
Address[] cc = new Address[] {
new InternetAddress("avdg#abc.com"),
new InternetAddress("saxenasaral#gmail.com")};
emailMessage.addRecipients(Message.RecipientType.CC, cc);
emailMessage.setFrom(new InternetAddress(from));
emailMessage.setSubject(subject);
//emailMessage.setContent(text, "text/html");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
messageBodyPart.setText(text);
// Now set the actual message
messageBodyPart.setText("This is message body");
//emailMessage.setContent(emailMessage, "text/html");
//emailMessage.setText(text);
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "c:\\SettingupRulesin outlook2003.pdf";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
// Send the complete message parts
emailMessage.setContent(multipart);
emailSession.setDebug(true);
// Set text message part
multipart.addBodyPart(messageBodyPart);
Transport.send(emailMessage);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Taken from the tutorial: http://itextpdf.com/examples/iia.php?id=219
public static byte[] USER = "password 1234".getBytes();
public static byte[] OWNER = "password 1234".getBytes();
public void encryptPdf(String filename, String filename) throws IOException, DocumentException {
PdfReader reader = new PdfReader(filename);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileName));
stamper.setEncryption(USER, OWNER,
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
}
Add encryptPdf(fileName, fileName); after the file string has been declared.
Edit: Used byte[] objects for password names. The usage of strings have been deprecated from this version of iText for encryption purposes.

Related

Create a draft with PDF file as attachment using Gmail API in Java

I'm trying to create a draft with an attachment in Java using Gmail API.
Creating a basic draft works, so I've eliminated any permission problem.
I've used code here as an inspiration but cannot get it to work.
Here's what I did so far:
public String generateGmailDraft(EmailRequestDto emailRequestDto, String quoteId)
throws MessagingException, IOException, GeneralSecurityException {
// The attachment is a PDF file
AttachmentDto lastQuoteData = getLastQuotePdfData(quoteId);
MimeMessage email = createMimeMessage(emailRequestDto, lastQuoteData);
Message messageWithEmail = createMessageWithEmail(email);
Draft draft = new Draft();
draft.setMessage(messageWithEmail);
// this works
Gmail gmail = gmail(googleGmailCredentialProperties);
log.debug("attempting to send mail");
draft = gmail.users().drafts().create(emailRequestDto.getFrom(), draft).execute();
log.debug("Draft id: {}", draft.getMessage().getId());
log.debug(draft.toPrettyString());
return draft.getMessage().getId();
}
From Google example, I created a MIME message, but this is probably where the problem lies:
/**
* Create a MimeMessage using the parameters provided
* #return the MimeMessage to be used to send email
* #throws MessagingException
*/
private MimeMessage createMimeMessage(EmailRequestDto requestDto, AttachmentDto attachment)
throws MessagingException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(requestDto.getFrom()));
email.addRecipient(javax.mail.Message.RecipientType.TO, ew InternetAddress(requestDto.getTo()));
email.setSubject(requestDto.getSubject());
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setHeader("Content-Type", "multipart/alternative");
messageBodyPart.setText(requestDto.getBody()); // Setting the actual message
// Create a multipart message and set text message part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Try to add an attachment
MimeBodyPart attachmentBP = new MimeBodyPart();
attachmentBP.setFileName(attachment.fileName);
ByteArrayOutputStream baos = attachmentToByteArrayOutputStream(attachment.file);
DataSource dataSrc = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
attachmentBP.setDataHandler(new DataHandler(dataSrc));
multipart.addBodyPart(attachmentBP);
// Send the complete message parts
email.setContent(multipart);
return email;
}
This private class hopefully provides everything needed for the attachment, when used, all private fields are correctly filled.
/**
AttachmentDTO returns everything needed to create an attachment
- file
- mimeype
- filename
- inputstream : used because file can come from different sources in the app.
*/
private static final class AttachmentDto {
private final InputStream inputStream;
private final String fileName;
private File file;
private String mimeType;
private AttachmentDto(InputStream inputStream, String fileName) {
this.inputStream = inputStream;
this.fileName = fileName;
File outputFile = new File(fileName);
try (OutputStream out = new FileOutputStream(outputFile)) {
IOUtils.copy(inputStream, out);
file = outputFile;
mimeType = Files.probeContentType(outputFile.toPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getInputStream() {
return inputStream;
}
public String getFileName() {
return fileName;
}
public File getFile() {
return file;
}
public String getMimeType() {
return mimeType;
}
}
Current state:
code gets stuck on gmail.users().drafts().create(emailRequestDto.getFrom(), draft).execute(); and never returns
following the link above, I also tried to encode the attachment as Base64, then use
public Gmail.Users.Drafts.Create create(
String userId,
Draft content,
AbstractInputStreamContent mediaContent) throws java.io.IOException
which is, I suppose, the counterpart to use when you have an attachment.
When I use this, draft gets created in my mailbox but without the attachment.
Any help appreciated, thank you.
Try something similar to this:
private MimeMessage createEmailWithAttachment(String to,
String subject,
String bodyText,
File file) throws MessagingException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(bodyText, "text/plain");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
mimeBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(file.getName());
multipart.addBodyPart(mimeBodyPart);
email.setContent(multipart);
return email;
}

How to create pdf file and send in mail of spring boot application

I am trying to send email with created pdf document as the attachment, the environment i am working is the REST based java spring boot application,
Actually i know how to send email with the thymeleaf template engine, but how can i create a pdf document in memory, and send it as a attachment, this is the code that i am using for sending email.
Context cxt = new Context();
cxt.setVariable("doctorFullName", doctorFullName);
String message = templateEngine.process(mailTemplate, cxt);
emailService.sendMail(MAIL_FROM, TO_EMAIL,"Subject", "message");
and this this the sendmail() function
#Override
public void sendPdfMail(String fromEmail, String recipientMailId, String subject, String body) {
logger.info("--in the function of sendMail");
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
try {
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setSubject(subject);
message.setFrom(fromEmail);
message.setTo(recipientMailId);
message.setText(body, true);
FileSystemResource file = new FileSystemResource("C:\\xampp\\htdocs\\project-name\\logs\\health360-logging.log");
message.addAttachment(file.getFilename(), file);
this.mailSender.send(mimeMessage);
logger.info("--Mail Sent Successfully");
} catch (MessagingException e) {
logger.info("--Mail Sent failed ---> " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
Actually i need to create a kind of report with 2-3 pages as pdf file, and send in mail.
Also i need to send multiple pdf reports, in the mail, how can i do this, can you friends help me on this, i found something called jasper, is it something related to my environment,
This is how you can send a mail:
public void email() {
String smtpHost = "yourhost.com"; //replace this with a valid host
int smtpPort = 587; //replace this with a valid port
String sender = "sender#yourhost.com"; //replace this with a valid sender email address
String recipient = "recipient#anotherhost.com"; //replace this with a valid recipient email address
String content = "dummy content"; //this will be the text of the email
String subject = "dummy subject"; //this will be the subject of the email
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", smtpPort);
Session session = Session.getDefaultInstance(properties, null);
ByteArrayOutputStream outputStream = null;
try {
//construct the text body part
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(content);
//now write the PDF content to the output stream
outputStream = new ByteArrayOutputStream();
writePdf(outputStream);
byte[] bytes = outputStream.toByteArray();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
pdfBodyPart.setFileName("test.pdf");
//construct the mime multi part
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(textBodyPart);
mimeMultipart.addBodyPart(pdfBodyPart);
//create the sender/recipient addresses
InternetAddress iaSender = new InternetAddress(sender);
InternetAddress iaRecipient = new InternetAddress(recipient);
//construct the mime message
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSender(iaSender);
mimeMessage.setSubject(subject);
mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
mimeMessage.setContent(mimeMultipart);
//send off the email
Transport.send(mimeMessage);
System.out.println("sent from " + sender +
", to " + recipient +
"; server = " + smtpHost + ", port = " + smtpPort);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
//clean off
if(null != outputStream) {
try { outputStream.close(); outputStream = null; }
catch(Exception ex) { }
}
}
}
You can see that we create a MimeBodyPart with a DataSource created from bytes that resulted from a method named writePdf():
public void writePdf(OutputStream outputStream) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
Paragraph paragraph = new Paragraph();
paragraph.add(new Chunk("hello!"));
document.add(paragraph);
document.close();
}
Since we use a ByteOutputStream instead of a FileOutputStream no file is written to disk.

JavaMail Password Protected Attachment

I am able to use Apache POI to create a password protected .xls file successfully. However, when I use JavaMail to send it as an attachment, the file I receive in the recipient email address is no longer password protected. Does anyone know why this may be happening?
final String fname = "sample.xls";
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
POIFSFileSystem poiFileSystem = null;
FileOutputStream fileOut = null;
try {
fileInput = new FileInputStream(fname);
bufferInput = new BufferedInputStream(fileInput);
poiFileSystem = new POIFSFileSystem(bufferInput);
Biff8EncryptionKey.setCurrentUserPassword("secret");
final HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
final HSSFSheet sheet = workbook.getSheetAt(0);
final HSSFRow row = sheet.createRow(0);
final Cell cell = row.createCell(0);
cell.setCellValue("THIS WORKS!");
fileOut = new FileOutputStream(fname);
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
workbook.close();
}
catch (final Exception ex){
System.out.println(ex.getMessage());
}
finally{
try{
bufferInput.close();
}
catch (final IOException ex){
System.out.println(ex.getMessage());
}
try {
fileOut.close();
}
catch (final IOException ex) {
System.out.println(ex.getMessage());
}
}
// Recipient's email ID needs to be mentioned.
final String to = "example#example.com";
// Sender's email ID needs to be mentioned
final String from = "example#example.com";
final String username = "example";//change accordingly
final String password = "example";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
final String host = "example";
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "example");
// Get the Session object.
final Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
final Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
final Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
final String filename = "sample.xls";
final DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (final MessagingException e) {
throw new RuntimeException(e);
}
I believe I was not doing the encryption correctly. I used the code here instead: http://www.quicklyjava.com/create-password-protected-excel-using-apache-poi/. It resolved the issue.

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