Send an email with a PDF attachment via JavaMail


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


Create PDF file

Create a PDF file using pdfbox


First of all, make pdfbox available in maven.



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);

        //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.newLineAtOffset(0, PDRectangle.A4.getHeight() - 12f);
		contentStream.setFont(font, 12);

		contentStream.setFont(font2, 15);


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

        // ----When creating a real file----
        // --------------------------------
	} catch (Exception e) {
	} finally {
		if (document != null) {
			try {
			} catch (Exception e) {
		if (collection != null) {
			try {
			} catch (Exception e) {
    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.


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



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();
		properties.put("", HOST);
		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));

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

			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));



		} catch (Exception e) {
			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.