Send an email with a PDF attachment via JavaMail

Overview

Send an email with a PDF attachment using JavaMail and pdfbox. Explains how to create a PDF file and how to send an email.

environment

Create PDF file

Create a PDF file using pdfbox

Preparation

First of all, make pdfbox available in maven.

pom.xml


<dependency>
  <groupId>org.apache.pdfbox</groupId>
  <artifactId>pdfbox</artifactId>
  <version>2.0.13</version>
</dependency>

PDF file creation code

Now let's create a PDF file. We will introduce the case of using an actual file and the case of using InputStream. This time I want to send an email without generating a real file, so I will write it with a method that returns ByteArrayInputStream.

public ByteArrayInputStream createDocument() {
	PDDocument document = null;
	TrueTypeCollection collection = null;
        ByteArrayInputStream inputStream;

	try {
        //Create a PDF base. This time with A4.
		document = new PDDocument();
		PDPage page = new PDPage(PDRectangle.A4);
		document.addPage(page);

        //Japanese cannot be used unless the font is loaded, so load it.
        //Mac has a different path.
		PDFont font = PDType1Font.TIMES_BOLD;
		File file = new File("C:/Windows/Fonts/msmincho.ttc");
        collection = new TrueTypeCollection(file);
        PDFont font2 = PDType0Font.load(document, collection.getFontByName("MS-Mincho"), true);

        //Create the contents of the page
		PDPageContentStream contentStream = new PDPageContentStream(document, page);
        //Create a single text by specifying the font and position.
        //The bottom left of the page is the base(0, 0)Will be.
		contentStream.beginText();
		contentStream.newLineAtOffset(0, PDRectangle.A4.getHeight() - 12f);
		contentStream.setFont(font, 12);
		contentStream.showText("firstText");
		contentStream.endText();

		contentStream.beginText();
		contentStream.newLine();
		contentStream.setFont(font2, 15);
		contentStream.showText("secondText");
		contentStream.endText();

		contentStream.close();

		//Create a PDF file.
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        document.save(out);
        inputStream = new ByteArrayInputStream(out.toByteArray());

        // ----When creating a real file----
        // document.save("sample.pdf");
        // --------------------------------
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (document != null) {
			try {
				document.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (collection != null) {
			try {
				collection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
    return inputStream;
}

If you write the code of "When executing the actual file", the PDF file will be generated at this stage.

send e-mail

Then use JavaMail to send the email.

Preparation

This also adds a description so that it can be used with maven.

pom.xml


<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4.7</version>
</dependency>

Install FakeSMTP

We will use FakeSMTP as the SMTP server for development this time. Please refer to link for how to use it.

By the way, I stopped using Gmail because I couldn't authenticate from the local environment without lowering the security.

Email sending code

Now, let's write the code to send an email. Receive the InputStream of the PDF created earlier as an argument and use it.

public void sendRawMail(final String subject, ByteArrayInputStream attachement) {
        //Property settings
		Properties properties = System.getProperties();
		//host
		properties.put("mail.smtp.host", HOST);
		//Authentication
		properties.put("mail.smtp.auth", "true");
		//Port designation (submission port)
		properties.put("mail.smtp.port", "25");
		//Encryption with STARTTLS
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.smtp.starttls.enable", "false");
		properties.put("mail.smtp.debug", "true");
		//time out
		properties.put("mail.smtp.connectiontimeout", "10000");
		properties.put("mail.smtp.timeout", "10000");

		try {
            //Creating a session.
			final Session session = Session.getInstance(properties , new javax.mail.Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication(){
                    //When using Gmail etc., specify the user name and password as arguments.
                    return new PasswordAuthentication("", "");
                }
            });
			final Message message = new MimeMessage(session);

			//Basic information
			message.setFrom(new InternetAddress("Sender email address"));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("Destination email address", false));
            //title
			message.setSubject(subject);

			//Text
			final MimeMultipart multipart = new MimeMultipart("mixed");
            //Body text
			final MimeBodyPart textPart = new MimeBodyPart();
			textPart.setText("Body text", "UTF-8");

            //Attachment
			final MimeBodyPart attPart = new MimeBodyPart();
            //When using a real file, create a DataSource with the real file
			final DataSource dataSource = new ByteArrayDataSource(attachement, "application/pdf");
			attPart.setDataHandler(new DataHandler(dataSource));
			attPart.setFileName("test.pdf");

			multipart.addBodyPart(textPart);
			multipart.addBodyPart(attPart);

			message.setContent(multipart);

			//Send
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
			throw new InternalServerErrorException(e);
		}
	}

The method execution will send an email with a PDF attached.

Recommended Posts

Send an email with a PDF attachment via JavaMail
Send an email from gmail with Ruby
Send an email using JavaMail on AWS
Ruby: Send email with Starttls
[Spring Boot] Send an email
Send email with spring boot
[2020 version] How to send an email using Android Studio Javamail
Invoke the character string passed as an argument as a method with send
I made an app to scribble with PencilKit on a PDF file
[Java] Send an email using Amazon SES
Send an email when an ERROR level log occurs with the logback SMTP Appender
I want to send an email in Java.