Spring Boot API - Send email with attachment from URL - java

This is what I have so far. I think I need a line like: helper.addAttachment(attachment); in there, but that doesn't compile. I just can't figure out the syntax of how to add this attachment. Anyone have any tips? Thanks!
#RequestMapping(value = "/api/sendemailsubmitted")
public void sendEmailSubmitted(#RequestBody VerifyInfo newVerifyInfo) throws MessagingException, MalformedURLException {
MimeMessage message = sender.createMimeMessage();
String username = newVerifyInfo.getUsername();
// Enable the multipart flag!
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Part attachment = new MimeBodyPart();
URL url = new URL("https://www.url.com/applicationsubmitted.pdf");
attachment.setDataHandler(new DataHandler(url));
attachment.setDisposition(Part.ATTACHMENT);
attachment.setFileName(url.getFile());
helper.setTo(username);
helper.setFrom("AdmissionsApplication#gmail.com");
helper.setText("<html><body>" +
"Please see attachment" +
"</body></html>", true);
helper.setSubject("Begin Your Journey!");
sender.send(message);
}

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/javamail/MimeMessageHelper.html
As you can see here you can just do a message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
No need to create MimeBodyPart MimeBodyPart is used to add it to javax.mail.internet.MimeMultipart and then add it to javax.mail.internet.MimeMessage, however, you are using Spring with org.springframework.mail.javamail.MimeMessageHelper

Related

Javamail doesn't send email with larger attachments

I want to send an email using Javamail with 2 attachments. One of them is a json file, and the other one is a txt file (logcat.txt). The logcat.txt is about 1mb in size.
It doesn't send any email if I have the addAttachment(multipart,reportPath,"logcat.txt"); in my code. If I remove addAttachment(multipart,reportPath,"logcat.txt"); it works.
When the json file gets larger, at one point about 500kb, it doesn't send either.
My code:
public synchronized void sendReport(String subject, String body, String filepath, String filename, String reportPath, String sender, String recipients){
try {
Multipart multipart = new MimeMultipart("mixed"); //try adding "mixed" here as well but it doesn't work
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
//body
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setText(body);
Log.d(TAG, "sendReport: " + reportPath);
//this prints sendReport: /storage/emulated/0/Android/data/**app package name**/files/LOG-1472631395.json
Log.d(TAG, "sendReport: " + filepath);
//sendReport: /storage/emulated/0/Android/data/**app package name**/files/logcat.txt
addAttachment(multipart,filepath,filename);
addAttachment(multipart,reportPath,"logcat.txt");
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addAttachment(Multipart multipart, String filepath, String filename) throws MessagingException
{
DataSource source = new FileDataSource(filepath);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
I also use another method to send attachments but it doesn't work either:
private static void addAttachment(Multipart multipart, String filepath, String filename) throws Exception
{
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.attachFile(filepath);
mimeBodyPart.setFileName(filename);
multipart.addBodyPart(mimeBodyPart);
}
Does anyone have an idea how to fix this? Thank you in advance.
//In this list set the path from the different files you want to attach
String[] attachments;
Multipart multipart = new MimeMultipart();
//Add attachments
if(attachments != null && attachments.length > 0) {
for (String str : attachments) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(str);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
}
}
message.setContent(multipart);
I don't have problems uploading huge files, you can try this code.
I used a private mail server of my customer to send emails, and it doesn't show any errors that I can see (because it is a public mail server). I then use Google Mail server, and this is a reply from gmail server to my email account:
Technical details of permanent failure: Google tried to deliver your
message, but it was rejected by the server for the recipient domain
mailinator.com by mail2.mailinator.com. [45.79.147.26].
The error that the other server returned was: 552 5.3.4 Message size
exceeds fixed limit
So this is because the domain mailinator.com has some message size limit so it doesn't appear. I then send things to a gmail email account and it works.

Amazon SES custom header List-Unsubscribe isn't working

I'm tryin to add the "List-Unsubscribe" header in my sent emails (through amazon ses) but when i see the received email there's no such header in it. I need it to reduce the number of spam complaints and to improve deliverability and reputation.
SendEmailRequest sendEmailRequest = new SendEmailRequest();
sendEmailRequest.putCustomRequestHeader(UNSUBSCRIBE_HEADER, unsuscribeURL);
PS: Using others providers such as Mandrill or Sendgrid it works, but i really need it at amazon
So... i found a workaround.
If you want to add a custom header to your message, always use a RawMessage, not a simple one.
Something like this:
SendRawEmailRequest sendRawEmailRequest = new SendRawEmailRequest();
RawMessage rawMessage = null;
rawMessage = buildSimpleRawMessage(...);
sendRawEmailRequest.setRawMessage(rawMessage);
private RawMessage buildSimpleRawMessage(String subject, String message, Attachment attachment) {
RawMessage rawMessage = null;
try {
// JavaMail representation of the message
Session s = Session.getInstance(new Properties(), null);
MimeMessage mimeMessage = new MimeMessage(s);
// Subject
mimeMessage.setSubject(subject);
// Add a MIME part to the message
MimeMultipart mimeBodyPart = new MimeMultipart();
BodyPart part = new MimeBodyPart();
part.setContent(message, "text/html");
mimeBodyPart.addBodyPart(part);
// Add a attachement to the message
if(attachment!=null){
part = new MimeBodyPart();
DataSource source = null;
source = new ByteArrayDataSource(attachment.getBuf(), attachment.getMimeType());
part.setDataHandler(new DataHandler(source));
part.setFileName(attachment.getFileName());
mimeBodyPart.addBodyPart(part);
}
mimeMessage.setContent(mimeBodyPart);
mimeMessage.addHeader(UNSUBSCRIBE_HEADER, unsubscribeURL);
// Create Raw message
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mimeMessage.writeTo(outputStream);
rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
} catch (Exception e) {
logger.error("There was a problem creating mail attachment", e);
throw Throwables.propagate(e);
}
return rawMessage;
}

mail is not sent by app-engine it stuck in Task Queue no error is generated

I've used github project jappstart https://github.com/taylorleese/google-app-engine-jappstart
as an example but after deploying application into app-engine in prod can't make application to send authorisation emails.
As well no Unauthorised sender error is generated in app-engine logs so looks like I'm using correct sender email. I realised that in Task Queues mail queue is generated but pressing run now button is not helping :/ Any Idea ?
prod properties file
google.app.id= -Application Identifier-
google.app.version=1
google.jsapi.http.key=enterKey
google.jsapi.https.key=enterKey
application.secureChannel=https
application.hostname= -Application Identifier Alias-
jquery.ver=1.7.1
mail.fromAddress= -owner/admin email-
ActivationEmail method
public final void sendActivationEmail(final UserAccount user,
final String locale)
throws MessagingException {
final Properties props = new Properties();
final Session session = Session.getDefaultInstance(props, null);
final Message message = new MimeMessage(session);
final Multipart multipart = new MimeMultipart();
final MimeBodyPart htmlPart = new MimeBodyPart();
final MimeBodyPart textPart = new MimeBodyPart();
message.setFrom(new InternetAddress(getFromAddress()));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(user.getEmail()));
message.setSubject(messageSource.getMessage("mail.subject", null,
new Locale(locale)));
textPart.setContent(messageSource.getMessage("mail.body.txt",
new Object[] {getHostname(), user.getActivationKey()},
new Locale(locale)), "text/plain");
htmlPart.setContent(messageSource.getMessage("mail.body.html",
new Object[] {getHostname(), user.getActivationKey()},
new Locale(locale)), "text/html");
multipart.addBodyPart(textPart);
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
Transport.send(message);
}

How Can I put a HTML link Inside an email body?

I have an application that can send mails, implemented in Java. I want to put a HTML link inside de mail, but the link appears as normal letters, not as HTML link...
How can i do to inside the HTML link into a String? I need special characters? thank you so much
Update:
HI evereybody! thanks for oyu answers! Here is my code:
public static boolean sendMail(Properties props, String to, String from,
String password, String subject, String body)
{
try
{
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect(from, password);
t.sendMessage(message, message.getAllRecipients());
// Cierre.
t.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
And here the body String:
String link = "ACTIVAR CUENTA";
But in the received message the link appears as the link string, not as HTML hyperlink! I don't understand what happens...
Any solution?
Adding the link is as simple as adding the text inside the string. You should set your email to support html (it depends on the library you are using), and you should not escape your email content before sending it.
Update: since you are using java.mail, you should set the text this way:
message.setText(body, "UTF-8", "html");
html is the mime subtype (this will result in text/html). The default value that is used by the setText(string) method is plain
I'm just going to answer in case this didn't work for someone else.
I tried Bozho's method and for some reason the email wouldn't send when I did the setText on the message as a whole.
I tried
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(body, "text/html");
but this came as an attachment in Outlook instead of in the usual text. To fix this for me, and in Outlook, instead of doing the mbp.setContent and message.setText, I just did a single setText on the message body part. ie:
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(messageBody,"UTF-8", "html");
With my code for the message looking like this:
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for(String str : to){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(str));
}
message.setSubject(subject);
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(messageBody,"UTF-8","html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Appending "http://" before the URL worked for me.
We can create html link in the email body by using java code.In my case I am developing reset password where I should create link and send to the user through the mail.you will create one string.With in a string you type all the url.If you add the http to the that .it behaves like link with in the mail.
Ex:String mailBody ="http://localhost:8080/Mail/verifytoken?token="+ token ;
you can send some value with url by adding query string.Her token has some encrypted value.
put mailBody in your mail body parameter.
ex": "Hi "+userdata.getFirstname()+
"\n\n You have requested for a new password from the X application. Please use the below Link to log in."+
"\n\n Click on Link: "+mailBody);
The above is the string that is parameter that you have to pass to your mail service.Email service takes parameters like from,to,subject,body.Here I have given body how it should be.you pass the from ,to,subject values according to your cast
you can do right way it is working for me.
public class SendEmail
{
public void getEmail(String to,String from, String userName,String password,Properties props,String subject,String messageBody)
{
MimeBodyPart mimeBodyPart=new MimeBodyPart();
mimeBodyPart.setContent(messageBody,"text/html");
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
Session session=Session.getInstance(props,new Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(userName,password);
}
});
try{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setContent(multipart);
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
message.setSubject("Have You got Mail!");
message.setText(messageBody,"UTF-8","html");
Transport.send(message);
}
catch(MessagingException ex){System.out.println(ex)}
public static void main(String arg[]){
SendEmail sendEmail=new SendEmail();
String to = "XXXXXXX#gmail.com";
String from = "XXXXXXXX#gmail.com";
final String username = "XXXXX#gmail.com";
final String password = "XXXX";
String subject="Html Template";
String body = "<i> Congratulations!</i><br>";
body += "<b>Your Email is working!</b><br>";
body += "<font color=red>Thank </font>";
String host = "smtp.gmail.com";
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", "587");
sendEmail.getEmail(to,from,username,password,props,subject,body);
}
}

Inline images in email using JavaMail

I want to send an email with an inline image using javamail.
I'm doing something like this.
MimeMultipart content = new MimeMultipart("related");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(message, "text/html; charset=ISO-8859-1");
content.addBodyPart(bodyPart);
bodyPart = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource(image, "image/jpeg");
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setHeader("Content-Type", "image/jpeg; name=image.jpg");
bodyPart.setHeader("Content-ID", "<image>");
bodyPart.setHeader("Content-Disposition", "inline");
content.addBodyPart(bodyPart);
msg.setContent(content);
I've also tried
bodyPart.setHeader("inline; filename=image.jpg");
and
bodyPart.setDisposition("inline");
but no matter what, the image is being sent as an attachment and the Content-Dispostion is turning into "attachment".
How do I send an image inline in the email using javamail?
Your problem
As far as I can see, it looks like the way you create the message and everything is mostly right! You use the right MIME types and everything.
I am not sure why you use a DataSource and DataHandler, and have a ContentID on the image, but you need to complete your question for me to be able to troubleshoot more. Especially, the following line:
bodyPart.setContent(message, "text/html; charset=ISO-8859-1");
What is in message? Does it contains <img src="cid:image" />?
Did you try to generate the ContentID with String cid = ContentIdGenerator.getContentId(); instead of using image
Source
This blog article taught me how to use the right message type, attach my image and refer to the attachment from the HTML body: How to Send Email with Embedded Images Using Java
Details
Message
You have to create your content using the MimeMultipart class. It is important to use the string "related" as a parameter to the constructor, to tell JavaMail that your parts are "working together".
MimeMultipart content = new MimeMultipart("related");
Content identifier
You need to generate a ContentID, it is a string used to identify the image you attached to your email and refer to it from the email body.
String cid = ContentIdGenerator.getContentId();
Note: This ContentIdGenerator class is hypothetical. You could create one or inline the creation of content IDs. In my case, I use a simple method:
import java.util.UUID;
// ...
String generateContentId(String prefix) {
return String.format("%s-%s", prefix, UUID.randomUUID());
}
HTML body
The HTML code is one part of the MimeMultipart content. Use the MimeBodyPart class for that. Don't forget to specify the encoding and "html" when you set the text of that part!
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setText(""
+ "<html>"
+ " <body>"
+ " <p>Here is my image:</p>"
+ " <img src=\"cid:" + cid + "\" />"
+ " </body>"
+ "</html>"
,"US-ASCII", "html");
content.addBodyPart(htmlPart);
Note that as a source of the image, we use cid: and the generated ContentID.
Image attachment
We can create another MimeBodyPart for the attachment of the image.
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile("resources/teapot.jpg");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(imagePart);
Note that we use the same ContentID between < and > and set it as the image's ContentID. We also set the disposition to INLINE to signal that this image is meant to be displayed in the email, not as an attachment.
Finish message
That's it! If you create an SMTP message on the right session and use that content, your email will contain an embedded image! For instance:
SMTPMessage m = new SMTPMessage(session);
m.setContent(content);
m.setSubject("Mail with embedded image");
m.setRecipient(RecipientType.TO, new InternetAddress("your#email.com"));
Transport.send(m)
Let me know if that works for you! ;)
Why don't you try something like this?
MimeMessage mail = new MimeMessage(mailSession);
mail.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File("complete path to image.jpg"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment.getName());
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(messageBodyPart);
mail.setContent(multipart);
in the message, have a
<img src="image.jpg"/>
tag and you should be ok.
Good Luck
This worked for me:
MimeMultipart rootContainer = new MimeMultipart();
rootContainer.setSubType("related");
rootContainer.addBodyPart(alternativeMultiPartWithPlainTextAndHtml); // not in focus here
rootContainer.addBodyPart(createInlineImagePart(base64EncodedImageContentByteArray));
...
message.setContent(rootContainer);
message.setHeader("MIME-Version", "1.0");
message.setHeader("Content-Type", rootContainer.getContentType());
...
BodyPart createInlineImagePart(byte[] base64EncodedImageContentByteArray) throws MessagingException {
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-Type", "image/jpeg");
headers.addHeader("Content-Transfer-Encoding", "base64");
MimeBodyPart imagePart = new MimeBodyPart(headers, base64EncodedImageContentByteArray);
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.setContentID("<image>");
imagePart.setFileName("image.jpg");
return imagePart;
If you are using Spring use MimeMessageHelper to send email with inline content (References).
Create JavaMailSender bean or configure this by adding corresponding properties to application.properties file, if you are using Spring Boot.
#Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", authEnable);
props.put("mail.smtp.starttls.enable", starttlsEnable);
//props.put("mail.debug", "true");
mailSender.setJavaMailProperties(props);
return mailSender;
}
Create algorithm to generate unique CONTENT-ID
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
public class ContentIdGenerator {
static int seq = 0;
static String hostname;
public static void getHostname() {
try {
hostname = InetAddress.getLocalHost().getCanonicalHostName();
}
catch (UnknownHostException e) {
// we can't find our hostname? okay, use something no one else is
// likely to use
hostname = new Random(System.currentTimeMillis()).nextInt(100000) + ".localhost";
}
}
/**
* Sequence goes from 0 to 100K, then starts up at 0 again. This is large
* enough,
* and saves
*
* #return
*/
public static synchronized int getSeq() {
return (seq++) % 100000;
}
/**
* One possible way to generate very-likely-unique content IDs.
*
* #return A content id that uses the hostname, the current time, and a
* sequence number
* to avoid collision.
*/
public static String getContentId() {
getHostname();
int c = getSeq();
return c + "." + System.currentTimeMillis() + "#" + hostname;
}
}
Send Email with inlines.
#Autowired
private JavaMailSender javaMailSender;
public void sendEmailWithInlineImage() {
MimeMessage mimeMessage = null;
try {
InternetAddress from = new InternetAddress(from, personal);
mimeMessage = javaMailSender.createMimeMessage();
mimeMessage.setSubject("Test Inline");
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo("test#test.com");
String contentId = ContentIdGenerator.getContentId();
String htmlText = "Hello,</br> <p>This is test with email inlines.</p><img src=\"cid:" + contentId + "\" />";
helper.setText(htmlText, true);
ClassPathResource classPathResource = new ClassPathResource("static/images/first.png");
helper.addInline(contentId, classPathResource);
javaMailSender.send(mimeMessage);
}
catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
RFC Specification could be found here(https://www.rfc-editor.org/rfc/rfc2392).
Firstly, email html content needs to format like : "cid:logo.png" when using inline pictures, see:
<td style="width:114px;padding-top: 19px">
<img src="cid:logo.png" />
</td>
Secondly, MimeBodyPart object needs to set property "disposition" as MimeBodyPart.INLINE, as below:
String filename = "logo.png"
BodyPart image = new MimeBodyPart();
image.setDisposition(MimeBodyPart.INLINE);
image.setFileName(filename);
image.setHeader("Content-ID", "<" +filename+">");
Be aware, Content-ID property must prefix and suffix with "<" and ">" perspectively, and the value off filename should be same with the content of src
of img tag without prefix "cid:"
Finally the whole code is below:
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("1234#gmail.com");
InternetAddress[] recipients = { "123#gmail.com"};
msg.setRecipients(Message.RecipientType.TO, recipients);
msg.setSubject("for test");
msg.setSentDate(new Date());
BodyPart content = new MimeBodyPart();
content.setContent(<html><body> <img src="cid:logo.png" /> </body></html>, "text/html; charset=utf-8");
String fileName = "logo.png";
BodyPart image = new MimeBodyPart();
image.setHeader("Content-ID", "<" +fileName+">");
image.setDisposition(MimeBodyPart.INLINE);
image.setFileName(fileName);
InputStream stream = MailService.class.getResourceAsStream(path);
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(stream), "image/png");
image.setDataHandler(new DataHandler(fds));
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(content);
multipart.addBodyPart(getImage(image1));
msg.setContent(multipart);
msg.saveChanges();
Transport bus = session.getTransport("smtp");
bus.connect("username", "password");
bus.sendMessage(msg, recipients);
bus.close();
I had some problems having inline images displayed in GMail and Thunderbird, made some tests and resolved with the following (sample) code:
String imagePath = "/path/to/the/image.png";
String fileName = imagePath.substring(path.lastIndexOf('/') + 1);
String htmlText = "<html><body>TEST:<img src=\"cid:img1\"></body></html>";
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<img1>");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Just some things to notice:
the "Content-ID" has to be built as specified in the RFCs (https://www.rfc-editor.org/rfc/rfc2392), so it has to be the part in the img tag src attribute, following the "cid:", enclosed by angle brackets ("<" and ">")
I had to set the file name
no need for width, height, alt or title in the img tag
I had to put the charset that way, because the one in the html was being ignored
This worked for me making inline images display for some clients and in GMail web client, I don't mean this will work everywhere and forever! :)
(Sorry for my english and for my typos!)
Below is the complete Code
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
private BodyPart createInlineImagePart() {
MimeBodyPart imagePart =null;
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(10000);
BufferedImage img=ImageIO.read(new File(directory path,"sdf_email_logo.jpg"));
ImageIO.write(img, "jpg", baos);
baos.flush();
String base64String=Base64.encode(baos.toByteArray());
baos.close();
byte[] bytearray = Base64.decode(base64String);
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-Type", "image/jpeg");
headers.addHeader("Content-Transfer-Encoding", "base64");
imagePart = new MimeBodyPart(headers, bytearray);
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.setContentID("<sdf_email_logo>");
imagePart.setFileName("sdf_email_logo.jpg");
}
catch(Exception exp)
{
logError("17", "Logo Attach Error : "+exp);
}
return imagePart;
}
MimeMultipart mp = new MimeMultipart();
//mp.addBodyPart(createInlineImagePart());
mp.addBodyPart(createInlineImagePart());
String body="<img src=\"cid:sdf_email_logo\"/>"
Use the following snippet:
MimeBodyPart imgBodyPart = new MimeBodyPart();
imgBodyPart.attachFile("Image.png");
imgBodyPart.setContentID('<'+"i01#example.com"+'>');
imgBodyPart.setDisposition(MimeBodyPart.INLINE);
imgBodyPart.setHeader("Content-Type", "image/png");
multipart.addBodyPart(imgBodyPart);
You need not in-line & base encode - you can attach traditionally and add the link to the main message's text which is of type text/html.
However remember to set the imgBodyPart's header's Content-Type to image/jpg or so right before appending to the main message (after you have attached the file).

Categories