question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to attach files to the email messages

See original GitHub issue

Whenever I try to send email with attachment via EmailService, I receive following exception:

java.lang.IllegalStateException: Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
	at org.springframework.mail.javamail.MimeMessageHelper.checkMultipart(MimeMessageHelper.java:383)
	at org.springframework.mail.javamail.MimeMessageHelper.getRootMimeMultipart(MimeMessageHelper.java:400)
	at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:998)
	at org.springframework.mail.javamail.MimeMessageHelper.addAttachment(MimeMessageHelper.java:1077)
	at it.ozimov.springboot.templating.mail.utils.EmailToMimeMessage.apply(EmailToMimeMessage.java:80)
	at it.ozimov.springboot.templating.mail.service.EmailServiceImpl.toMimeMessage(EmailServiceImpl.java:124)
	at it.ozimov.springboot.templating.mail.service.EmailServiceImpl.send(EmailServiceImpl.java:81)
...

I tried both plain text messages or created from Freemaker template, in both cases result is the same.

Code snippet:

@ActiveProfiles("service-test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ServicesTestsConfiguration.class)
@TestPropertySource(locations = "classpath:application-test.properties")
public class MailTest {

    @Autowired
    public EmailService emailService;

    @Value("${mail.from}")
    private String emailFrom;

    @Value("${mail.to}")
    private String emailTo;

    private final Charset charset = Charset.forName("UTF-8");

    @Test
    public void testMail() throws AddressException, CannotSendEmailException {
        final String testData = "col1,col2\n1,2\n3,4";
        final EmailAttachmentImplBuilder attachment = EmailAttachmentImpl.builder().attachmentName("test.csv")
                .attachmentData(testData.getBytes(charset)).mediaType(MediaType.TEXT_PLAIN);
        final Email email = EmailImpl.builder().from(new InternetAddress(emailFrom)).to(Lists.newArrayList(new InternetAddress(emailTo)))
                .subject("subject").body("").encoding(charset).attachments(Lists.newArrayList(attachment.build())).build();

        final Map<String, Object> modelObject = Maps.newHashMap();
        modelObject.put("instance", "FooBar");

        // doesn't work neither: emailService.send(email);
        emailService.send(email, "email_test.ftl", modelObject);
    }

}

Thanks for looking into the issue, Maciej

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:12 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
maciejlachcommented, Jan 9, 2017

@robertotru thanks! Plain text emails with attachments are now working fine.

With templated ones, original attachments are not present in the final message.

According to SO the email should have structure similar to this one:

multipart/mixed
    multipart/alternative
        text/plain
        multipart/related
            text/html
            image/jpeg
    application/pdf

It seems like method EmailServiceImpl#send(Email email, String template, Map<String, Object> modelObject, InlinePicture... inlinePictures) overwrites the original MimeMessage content and creates structure like:

multipart/related
    text/html
    image/jpeg
1reaction
maciejlachcommented, Jan 9, 2017

@robertotru thank you for looking into this.

Unfortunately, after upgrading to 0.3.6, I’m still having issue with attachments.

When using the freemarker template (emailService.send(email, "email_test.ftl", modelObject); in my code snippet), email is sent without any exceptions, but the attachment is missing when I view the email in my inbox:

Return-Path: <foo@mail.test>
Received: from ----- ([-----])
        by smtp.gmail.com with ESMTPSA id h15sm4452941ljb.46.2017.01.08.22.37.24
        for <foo@mail.test>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Sun, 08 Jan 2017 22:37:24 -0800 (PST)
From: "foo@mail.test" <foo@mail.test>
X-Google-Original-From: "foo@mail.test" <foo@mail.test>
Date: Mon, 9 Jan 2017 07:37:13 +0100 (CET)
To: foo@mail.test
Message-ID: <2133612542.3.1483943843982@lachoo-nb>
Subject: 65cb9087-08db-4a6b-b7ce-77446152fc4d
MIME-Version: 1.0
Content-Type: multipart/related; boundary="----=_Part_2_501530336.1483943833656"

------=_Part_2_501530336.1483943833656
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit

<!doctype html>
<html>
  <body>
    <p>Sent from: FooBar</p>
  </body>
</html>

------=_Part_2_501530336.1483943833656--

While using the library without templates: emailService.send(email);, I’m getting this exception:

org.springframework.mail.MailSendException: Failed messages: javax.mail.internet.ParseException: In Content-Type string <text>, expected '/', got null; message exception details (1) are:
Failed message 1:
javax.mail.internet.ParseException: In Content-Type string <text>, expected '/', got null
	at javax.mail.internet.ContentType.<init>(ContentType.java:104)
	at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1467)
	at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1131)
	at javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:515)
	at javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1490)
	at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2198)
	at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2159)
	at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:443)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:345)
	at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:340)
	at it.ozimov.springboot.templating.mail.service.EmailServiceImpl.send(EmailServiceImpl.java:72)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Unable to attach files in Outlook.com - Microsoft Support
Learn what you can do if you're unable to attach files or insrt images in Outlook.com.
Read more >
Can't Attach Files in Gmail? Fix It with Top 5 ways
One of the reasons you can't attach files in Gmail is that the browser is outdated. Therefore, you can update your browser to...
Read more >
I am not able to attach files in the gmail as the attach button is ...
the attach button just disappears in one second after clicking on it to attach files in gmail and this is not working in...
Read more >
Can't Attach Files in Outlook Email? Find Best 9 Solutions
Try These 4 Main Solutions First · Solution 1: Check File Size and Increase Attachment Limit · Solution 2: Compress the Attachment File...
Read more >
How To Fix Gmail Won't Attach Files Issue - The Droid Guy
Fix Unable to attach files in Gmail Error? · Solution 1: Check the file size · Solution 2: Try using the Gmail mobile...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found