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.
Related
i want to send to send the html content along with an attachment. So how can it be sent in same mail ?
Could someone guide me. Thanks
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.CC,new InternetAddress("username#abc.com"));
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(data, "text/html");
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "Data.xlsx";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setSubject("FOS Report");
message.setContent(multipart);
//send the message
Transport.send(message);
System.out.println("message sent successfully...");
}
catch (MessagingException e) {
e.printStackTrace();}
When you have two different types of contents, (binary and HTML in your case), you have to use Multipart for correct rendition.
You can learn about Multipart here: http://docs.oracle.com/javaee/6/api/javax/mail/Multipart.html
On how to work with JavaMail with Multipart, a very nice tutorial here:
https://www.programcreek.com/java-api-examples/javax.mail.Multipart
Please comment/ inbox if you require further assistance.
public static String sendMail(
String destino,
String texto,
String asunto,
byte[] formulario,
String nombre) {
Properties properties = new Properties();
try{
Session session = Session.getInstance(properties);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("reminder#companyname.com.ar"));
//Cargo el destino
if(destino!= null && destino.length > 0 && destino[0].length() > 0 ){
for (int i = 0; i < destino.length; i++) {
message.addRecipient(Message.RecipientType.TO,new InternetAddress(destino[i]));
}
}
//message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(asunto);
//I load the text and replace all the '&' for 'Enters' and the '#' for tabs
message.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));
Transport.send(message);
return "Mensaje enviado con éxito";
}catch(Exception mex){
return mex.toString();
}
}
Hello everyone.
I was trying to figure out how can I attach the PDF sent by parameters as formulario in the code previously shown.
The company used to do the following trick for this matter but they need to change it for the one previously shown:
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(
texto.replaceAll("&", "\n").replaceAll("#", "\t"));
//msg.setText(texto.replaceAll("&","\n").replaceAll("#","\t"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(
new DataHandler(
(DataSource) new InputStreamDataSource(formulario,
"EDD",
"application/pdf")));
messageBodyPart.setFileName(nombre + ".pdf");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(
"smtp.gmail.com",
"reminder#companyname.com.ar",
"companypassword");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return "Mensaje enviado con éxito";
} catch (Exception mex) {
return mex.toString();
Since you already can send emails, the adjust your code and add the following part to your code
// Create a default MimeMessage object.
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
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/home/file.pdf";
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....");
original code taken from here
Is formulario a byte array in both cases? If so, just rewrite the first block of code to construct the message using the technique in the second block of code. Or replace InputStreamDataSource with ByteArrayDataSource in the new version.
The sending email with attachment is similar to sending email but here the additional functionality is with message sending a file or document by making use of MimeBodyPart, BodyPart classes.
The process for sending mail with attachment involves session object, MimeBody, MultiPart objects. Here the MimeBody is used to set the text message and it is carried by MultiPart object. Because of MultiPart object here sending attachment.
try {
// Create a default MimeMessage object.
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("Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Please find the attachment below");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "D:/test.PDF";
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("Email Sent Successfully !!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
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);
}
}
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).
I have the following method to send an email, but I couldn't get the attached object, why ?
void Send_Email(String From,String To,String Subject,Text Message_Text,Contact_Info_Entry An_Info_Entry)
{
Properties props=new Properties();
Session session=Session.getDefaultInstance(props,null);
String htmlBody="<Html>Hi</Html>";
byte[] attachmentData;
Multipart multipart=new MimeMultipart();
BASE64Encoder BASE64_Encoder=new BASE64Encoder();
try
{
Message message=new MimeMessage(session);
message.setFrom(new InternetAddress(From,"NM-Java Admin"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(To,"Ni , Min"));
// You may need to encode the subject with this special method !
// message.setSubject(javax.mail.internet.MimeUtility.encodeText("Testing javamail with french : ��� "));
message.setSentDate(new Date());
message.setSubject(Subject);
MimeBodyPart messageBodyPart=new MimeBodyPart(); // Create the message part
messageBodyPart.setText(Message_Text.getValue()); // Fill message
multipart.addBodyPart(messageBodyPart);
MimeBodyPart htmlPart=new MimeBodyPart();
htmlPart.setContent(htmlBody,"text/html");
multipart.addBodyPart(htmlPart);
//setHTMLContent(message);
ByteArrayOutputStream bStream=new ByteArrayOutputStream();
ObjectOutputStream oStream=new ObjectOutputStream(bStream);
oStream.writeObject(An_Info_Entry);
// attachmentData=bStream.toByteArray();
// attachmentData=BASE64_Encoder.encode(bStream.toByteArray());
MimeBodyPart attachment=new MimeBodyPart();
attachment.setFileName(An_Info_Entry.Contact_Id);
attachment.setContent(BASE64_Encoder.encode(bStream.toByteArray()),"application/x-java-serialized-object");
multipart.addBodyPart(attachment);
setBinaryContent(message,BASE64_Encoder.encode(bStream.toByteArray()).getBytes());
message.setContent(multipart); // Put parts in message
message.setText(Message_Text.getValue()+" [ An_Info_Entry.Contact_Id = "+An_Info_Entry.Contact_Id+" ]");
Transport.send(message);
}
catch (Exception ex)
{
// ...
}
}
Probably because:
You're setting your content type as: text/html and you're really sending raw binary.
MimeBodyPart attachment=new MimeBodyPart();
attachment.setFileName(An_Info_Entry.Contact_Id);
attachment.setContent(attachmentData,"text/html"); // <-- Here
multipart.addBodyPart(attachment);
Even if you use the right content-type, you should encode the content as using base64 that way the attachment could make it trough the net.
// This
//attachmentData=bStream.toByteArray();
// should be something like:
attachmentData=Base64Coder.encode( bStream.toByteArray());