How to attach an object in an email with Java? - java

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

Related

Inline image shown as attachment : JavaMail

I am trying to send an email with an inline image, but the image is getting send as an attachment instead of inline.
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
String filename = "logo.jpeg";
mimeMessage.setFrom(new InternetAddress("Bridge"));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
MimeMultipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content, "text/html");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(resourceFile.getInputStream()), MediaType.IMAGE_JPEG_VALUE);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
messageBodyPart.setFileName(filename);
messageBodyPart.setHeader("Content-ID", "<logoimg>");
messageBodyPart.setHeader("Content-Type", MediaType.IMAGE_JPEG_VALUE);
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
javaMailSender.send(mimeMessage);
} catch (MailException | MessagingException | IOException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
And here is my HTML code for the image:
<img width="100" height="50" src="|cid:logoimg|" alt="phoenixlogo"/>
I have tried all the multipart types: "mixed", "relative", "alternative" but couldn't get it to work.
Here is image for same:
You don't want an inline image, you want an html body that references an attached image. For that you need a multipart/related message. See the JavaMail FAQ.
You need to add a separate MimeBodyPart: For Example
BodyPart imgPart = new MimeBodyPart();
DataSource ds = new FileDataSource("D:/image.jpg");
imgPart.setDataHandler(new DataHandler(ds));
imgPart.setHeader("Content-ID", "<the-img-1>");
multipart.addBodyPart(imgPart);
Then in the html you refer to the Image as:
<br>" + "<img src=\"cid:the-img-1\"/><br/>

Unable to send html content with attachment using java mail api

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.

How to attach a PDF in a mail using Java Mail?

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

Java email content is empty

I have snippet of codes where I send out email with excel file attachment. All works fine where I can see title and even the file attachment. The only thing does not appear is the email content. I have tested that my emailContent variable is not empty. What else can I do to make it appear ? I have even enabled this line of codes messageBodyPart.setText(emailContent); yet the same.
But if enabled this part multipart1.addBodyPart(emailContent); I get error
error: no suitable method found for addBodyPart(String)
multipart1.addBodyPart(emailContent);
try
{
Message emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(origin1));
emailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(receiptnt1));
emailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(receiptnt2));
emailMessage.setRecipients(Message.RecipientType.CC,InternetAddress.parse(cc1));
emailMessage.setSubject(emailTitle);
emailMessage.setText(emailContent);
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
//messageBodyPart.setText(emailContent);*/
Multipart multipart1 = new MimeMultipart();
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart1.addBodyPart(messageBodyPart);
// Put parts in message
emailMessage.setContent(multipart1);
//System.out.println("\n\nSend email :"+eMArray[0]);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
}
catch (Exception e)
{
System.out.println("Transport Problem");
e.printStackTrace();
}
You have initialized
BodyPart messageBodyPart = new MimeBodyPart();
Two times. And before the second initialization you're adding the body contents.
So remove the line
messageBodyPart = new MimeBodyPary();
Line and it will work fine.
Use the following code.
Message emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(origin1));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiptnt1));
emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiptnt2));
emailMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc1));
emailMessage.setSubject(emailTitle);
// emailMessage.setText(emailContent);
Multipart multipart1 = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(emailContent);
// Part two is attachment
BodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(filename);
multipart1.addBodyPart(attachment);
multipart1.addBodyPart(messageBodyPart);
// Put parts in message
emailMessage.setContent(multipart1);
//System.out.println("\n\nSend email :"+eMArray[0]);
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());

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

Categories