I prepare my message as MimeMessage and try it open in different mail clients. In all client my message looks good but in Outlook and in another one, it looks wrong
...
MimeMessage mimeMessage = new MimeMessage(session);
// Text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(email.getPlainMessage(), "text/plain");
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(email.getMessage(), "text/html");
//logo
PreencodedMimeBodyPart logo = new PreencodedMimeBodyPart(BASE_64_ENCODING);
logo.setHeader("Content-Type", IMAGE_PNG_CONTENT_TYPE + "; name=\"logo.png\"");
logo.setHeader("Content-ID", "<logo.png#01CFFF81.C72F8000>");
logo.setHeader("Content-Disposition", "inline; filename=\"logo.png\"");
logo.setHeader("Content-Transfer-Encoding", BASE_64_ENCODING);
logo.setContent(ENCODED_LOGO, IMAGE_PNG_CONTENT_TYPE);
// Create the Multipart. Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(logo);
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
if (Objects.nonNull(email.getFilesToAttach())) {
for (String filename : email.getFilesToAttach()) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename.substring(filename.lastIndexOf(File.separator) + 1));
mp.addBodyPart(messageBodyPart);
}
}
// Set Multipart as the message's content
mimeMessage.setContent(mp);
mimeMessage.setSubject(email.getSubject());
mimeMessage.setFrom(new InternetAddress(emailConfig.getNoReplyEmailAddress()));
if (!emailConfig.getNoReplyEmailAddress().equals(email.getFromAddress())) {
List<Address> replyTo = Arrays.asList(new InternetAddress(email.getFromAddress()));
mimeMessage.setReplyTo(replyTo.toArray(new Address[replyTo.size()]));
}
mimeMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email.getToAddress()));
mimeMessage.saveChanges();
...
And when I send it in outlook I see my logo as
but in another mail clients it looks good
How do I submit a pdf file to a generic e-mail from Java application?
You can Send E-Mail with PDF file as Attachment using reference of this -
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendMailWithAttachment
{
public static void main(String [] args)
{
String to="XYZ#abc.com"; //Email address of the recipient
final String user="ABC#XYZ.com"; //Email address of sender
final String password="xxxxx"; //Password of the sender's email
//Get the session object
Properties properties = System.getProperties();
//Here pass your smtp server url
properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password); } });
//Compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Aleart");
//Create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//Create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "YourPDFFileName.pdf";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//Create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//Set the multiplart object to the message object
message.setContent(multipart );
//Send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
You can also refer to JavaTPoint
delete the part :
//Here pass your smtp server url
properties.setProperty("mail.smtp.host",
"mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
And paste the code below :
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory", "587");
props.put("mail.smtp.port", "587"); //587
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
I am getting the syntax for the below line while trying to send the mail through SMTP .I tried in google but didnt get any relevant answer.
property.setProperty("mail.smtp.host",host);
CODE:
public class SendMail {
//Recipient Mail id
String to = "Receiver Mail ID";
//Sender Mail Id
String from = "Sender Mail ID";
//Sending email from the localhost
String host = "localhost";
//Get System Properties
Properties property = System.getProperties();
//Setup the mail server
property.setProperty("mail.smtp.host",host);
property.setProperty("mail.smtp.port" , "465");
//property.put("mail.smtp.auth", "true");
//Get the default session object
Session session = Session.getDefaultInstance(property);
try
{
//Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
//Set From: header field of the header
message.setFrom(new InternetAddress(from));
//Set To : header field of the header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set Subject : header field
message.setSubject("Automation Testing Report");
//Create the Message part
BodyPart messageBodypart = new MimeBodyPart();
//Enter the message in the Mail Body
messageBodypart.setText("***********Find the below for the Report****************");
//Create a Multipart Message
Multipart multipart = new MimeMultipart();
//Set Text message part
multipart.addBodyPart(messageBodypart);
//Part two is attachment
/*create the Message part*/
messageBodypart = new MimeBodyPart();
String filename = "E:\\Project\\jar\\Selenium Scripts\\Hybrid_Driven\\test-output\\emailable-report.html";
DataSource source = new FileDataSource(filename);
messageBodypart.setDataHandler(new DataHandler(source));
messageBodypart.setFileName(filename);
//set the text message part
multipart.addBodyPart(messageBodypart);
//Send the complete message part
message.setContent(multipart);
//Send message
Transport.send(message);
System.out.println("Mail has sent successfully");
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}
Please help me to resolve this issue.
You cannot put java code directly into a class. It needs to be within methods. The following is happily accepted by the compiler:
public class SendMail {
...
//Get System Properties
java.util.Properties property = System.getProperties();
void doSomething()
{
property.setProperty("mail.smtp.host", host);
property.setProperty("mail.smtp.port", "465");
...
}
}
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());
The following Java code is used to attach a file to an email. I want to send multiple files attachments through email. Any suggestions would be appreciated.
public class SendMail {
public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "mnmnn";
String from = "xyz#gmail.com";
String toAddress = "abc#gmail.com";
String filename = "C:/Users/hp/Desktop/Write.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtps.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("JavaMail Attachment");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try {
Transport tr = session.getTransport("smtps");
tr.connect(host, from, Password);
tr.sendMessage(message, message.getAllRecipients());
System.out.println("Mail Sent Successfully");
tr.close();
} catch (SendFailedException sfe) {
System.out.println(sfe);
}
}
}`
Well, it's been a while since I've done JavaMail work, but it looks like you could just repeat this code multiple times:
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
For example, you could write a method to do it:
private static void addAttachment(Multipart multipart, String filename)
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
Then from your main code, just call:
addAttachment(multipart, "file1.txt");
addAttachment(multipart, "file2.txt");
etc
UPDATE (March 2020)
With the latest JavaMailâ„¢ API (version 1.6 at the moment, JSR 919), things are much simpler:
void attachFile(File file)
void attachFile(File file, String contentType, String encoding)
void attachFile(String file)
void attachFile(String file, String contentType, String encoding)
Useful reading
Here is a nice and to the point tutorial with the complete example:
JavaMail - How to send e-mail with attachments
Multipart mp = new MimeMultipart();
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(body,"text/html");
mp.addBodyPart(mbp1);
if(filename!=null)
{
MimeBodyPart mbp2 = null;
FileDataSource fds =null;
for(int counter=0;counter<filename.length;counter++)
{
mbp2 = null;
fds =null;
mbp2=new MimeBodyPart();
fds = new FileDataSource(filename[counter]);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}
}
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
just add another block with using the filename of the second file you want to attach and insert it before the message.setContent(multipart) command
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
Have Array list al which has the list of attachments you need to mail and use the below given code
for(int i=0;i<al.size();i++)
{
System.out.println(al.get(i));
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource((String)al.get(i));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName((String)al.get(i));
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
File f = new File(filepath);
File[] attachments = f.listFiles();
// Part two is attachment
for( int i = 0; i < attachments.length; i++ ) {
if (attachments[i].isFile() && attachments[i].getName().startsWith("error")) {
messageBodyPart = new MimeBodyPart();
FileDataSource fileDataSource =new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
messageBodyPart.setFileName(attachments[i].getName());
messageBodyPart.setContentID("<ARTHOS>");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(messageBodyPart);
}
}
for (String fileName: files) {
MimeBodyPart messageAttachmentPart = new MimeBodyPart();
messageAttachmentPart.attachFile(fileName);
multipart.addBodyPart(messageAttachmentPart);
}
You have to make sure that you are creating a new mimeBodyPart for each attachment. The object is being passed by reference so if you only do :
MimeBodyPart messageAttachmentPart = new MimeBodyPart();
for (String fileName: files) {
messageAttachmentPart.attachFile(fileName);
multipart.addBodyPart(messageAttachmentPart);
}
it will attach the same file X number of times
#informatik01 posted an answer above with the link to the documentation where there is an example of this
Just add more files to the multipart.
This is woking 100% with Spring 4+. You will have to enable less secure option on your gmail account. Also you will need the apache commons package:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
#GetMapping("/some-mapping")
public void mailMethod(#RequestParam CommonsMultipartFile attachFile, #RequestParam CommonsMultipartFile attachFile2) {
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.auth", true);
mailProperties.put("mail.smtp.starttls.enable", true);
mailProperties.put("mail.smtp.ssl.enable", true);
mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
mailProperties.put("mail.smtp.socketFactory.fallback", false);
JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
javaMailSenderImpl.setJavaMailProperties(mailProperties);
javaMailSenderImpl.setHost("smtp.gmail.com");
javaMailSenderImpl.setPort(465);
javaMailSenderImpl.setProtocol("smtp");
javaMailSenderImpl.setUsername("*********#gmail.com");
javaMailSenderImpl.setPassword("*******");
javaMailSenderImpl.setDefaultEncoding("UTF-8");
List<CommonsMultipartFile> attachments = new ArrayList<>();
attachments.add(attachFile);
attachments.add(attachFile2);
javaMailSenderImpl.send(mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setTo(emailTo);
messageHelper.setSubject(subject);
messageHelper.setText(message);
if (!attachments.equals("")) {
for (CommonsMultipartFile file : attachments) {
messageHelper.addAttachment(file.getOriginalFilename(), file);
}
}
});
}
Multipart multipart = new MimeMultipart("mixed");
for (int alen = 0; attlen < attachments.length; attlen++)
{
MimeBodyPart messageAttachment = new MimeBodyPart();
fileName = ""+ attachments[attlen];
messageAttachment.attachFile(fileName);
messageAttachment.setFileName(attachment);
multipart.addBodyPart(messageAttachment);
}
After Java Mail 1.3 attaching file more simpler,
Just use MimeBodyPart methods to attach file directly or from a filepath.
MimeBodyPart messageBodyPart = new MimeBodyPart();
//messageBodyPart.attachFile(String filePath);
messageBodyPart.attachFile(File file);
multipart.addBodyPart(messageBodyPart);
Try this to read the file name from array
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
for(int i = 0 ; i < FilePath.length ; i++){
info("Attching the file + "+ FilePath[i]);
messageBodyPart.attachFile(FilePath[i]);
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
I do have a better alternative for sending Multiple files in a single mail off course. Mutipart class allows us to attain this feature quite easily. If you may not have any info about it then read it from here : https://docs.oracle.com/javaee/6/api/javax/mail/Multipart.html
The Multipart class provides us two same-name methods with different parameters off course, i.e. addBodyPart(BodyPart part) and addBodyPart(BodyPart part, int index). For 1 single file we may use the first method and for mutiple files we may use the second method (which takes two parameters).
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
message.setFrom(new InternetAddress(username));
for (String email : toEmails) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(email));
}
message.setSubject(subject);
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(typedMessage);
multipart.addBodyPart(messageBodyPart1, i);
i = i + 1;
for (String filename : attachedFiles) {
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(filename);
multipart.addBodyPart(messageBodyPart2, i);
i = i + 1;
}
message.setContent(multipart);
Transport.send(message);
Below is working for me:
List<String> attachments = new ArrayList<>();
attachments.add("C:/Users/dell/Desktop/file1.txt");
attachments.add("C:/Users/dell/Desktop/file2.txt");
attachments.add("C:/Users/dell/Desktop/file3.txt");
attachments.add("C:/Users/dell/Desktop/file4.txt");
attachments.add("C:/Users/dell/Desktop/file5.txt");
MimeMessage msg = new MimeMessage(session);
if (attachments !=null && !attachments.isEmpty() ) {
MimeBodyPart attachmentPart = null;
Multipart multipart = new MimeMultipart();
for(String attachment : attachments) {
attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File(attachment));
multipart.addBodyPart(attachmentPart);
}
multipart.addBodyPart(textBodyPart);
msg.setContent(multipart);
}
Transport.send(msg);