I am trying to write a program that constructs an email with 4 components within the body, an image at the top of the body, text below that, a table containing text (yet to do this, not in scope of question), and finally a 2nd image below the text & table. Currently my code is adding only the first MimeBodyPart as an INLINE image, all other MimeBodyParts (including the text) is getting attached to the email as an attachment, opposed to being contained in text within the body. The email is supposed to be saved locally before reviewing to be sent manual.
FYI, I am not familiar with html, so if its an issue with that please supply the answer/correct way to do what I am trying to achieve. Additionally if someone could include how to attach a 2×2 table and give pointers on how to size the columns/rows and fill them that would be awesome.
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailGenerator {
public MailGenerator() {
}
//Data = 0: Incident No, 1: Incident Type, 2: Full Location, 3: Site Code, 4: Description, 5: Start Date, 6: End Date
public void writeMail() {
try{
Message message = new MimeMessage(Session.getInstance(System.getProperties()));
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Testing");
//make it a draft!!
message.setHeader("X-Unsent", "1");
MimeBodyPart bodyText = new MimeBodyPart();
bodyText.setText("This is a test message");
Multipart multipart = new MimeMultipart();
// only the first bodypart here appears intext, commenting out the first brings the next into the body
uploadImage(multipart, "outage.png");
multipart.addBodyPart(bodyText);
uploadImage(multipart, "footer.png");
// integration
message.setContent(multipart);
// store file
message.writeTo(new FileOutputStream(new File("mail.eml")));
} catch (Exception e) {
System.out.println(e); //Lazy catching
}
}
public void uploadImage(Multipart multipart, String fileName) throws Exception {
String contentID = getContentID(fileName);
MimeBodyPart htmlImage = new MimeBodyPart();
htmlImage.setText(""
+ "<html>"
+ " <body>"
+ " <img src="cid:" + contentID + "" />"
+ " </body>"
+ "</html>"
,"US-ASCII", "html");
multipart.addBodyPart(htmlImage);
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(fileName);
imagePart.setContentID(contentID);
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
}
public String getContentID(String prefix) {
return String.format("%s-%s", prefix, UUID.randomUUID());
}
}