How to Attach Multiple Files to an Email Using Javamail

How to attach multiple files to an email using JavaMail?

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

How to send mail with multiple attachments in java

Create a simple method called, something like, attachFile, which takes a File, Multipart and MimeBodyPart as parameters...

public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart) {
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}

Call it as often as you need

File attachFiles[] = ...

if (attachFiles > 0) {
//attach file
attachFile(attachFiles[0], multipart, messageBodyPart);
if (attachFiles > 1) {
for (int index = 1; index < attachFiles.length; index++) {
attachFile(attachFiles[0], multipart, new MimeBodyPart());
}
}
}

as an example

Java: How do I attach multiple files to an email?

This is my own email utility class, check if that the sendEmail method works for you

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EMail {

public enum SendMethod{
HTTP, TLS, SSL
}

private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

public static boolean isValidEmail(String address){
return (address!=null && address.matches(EMAIL_PATTERN));
}

public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}

public static boolean sendEmail(final String recipients, final String from,
final String subject, final String contents,final String[] attachments,
final String smtpserver, final String username, final String password, final SendMethod method) {

Properties props = System.getProperties();
props.setProperty("mail.smtp.host", smtpserver);

Session session = null;

switch (method){
case HTTP:
if (username!=null) props.setProperty("mail.user", username);
if (password!=null) props.setProperty("mail.password", password);
session = Session.getDefaultInstance(props);
break;
case TLS:
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
case SSL:
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
});
break;
}

try {
MimeMessage message = new MimeMessage(session);

message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, recipients);
message.setSubject(subject);

Multipart multipart = new MimeMultipart();

BodyPart bodypart = new MimeBodyPart();
bodypart.setContent(contents, "text/html");

multipart.addBodyPart(bodypart);

if (attachments!=null){
for (int co=0; co<attachments.length; co++){
bodypart = new MimeBodyPart();
File file = new File(attachments[co]);
DataSource datasource = new FileDataSource(file);
bodypart.setDataHandler(new DataHandler(datasource));
bodypart.setFileName(file.getName());
multipart.addBodyPart(bodypart);
}
}

message.setContent(multipart);
Transport.send(message);

} catch(MessagingException e){
e.printStackTrace();
return false;
}
return true;
}
}

Java Mail - Attach multiple pdf file and send mail

Change

 String temp = new String(bytes);
byteArray[i] = temp;
bytes = outputStream.toByteArray();

to

 bytes = outputStream.toByteArray();
String temp = new String(bytes);
byteArray[i] = temp;

BTW, naming a String array "byteArray" is not a great choice. :-)

It would also be much better to just pass an array of byte arrays,
then use JavaMail's ByteArrayDataSource to add the attachment, but
I don't know if your Email class can handle that.

Converting the byte array to a String and then back to a byte array
risks corrupting the content.

Java Mail, sending multiple attachments not working

Multipart multipart = new MimeMultipart("mixed");
for (String str : attachment_PathList) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(str);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);

email sending with multiple attachments using MultipartFile

Try this:

attachPart.setContent(filePath.getBytes(), filePath.getContentType());
attachPart.setFileName(filePath.getOriginalFilename());
attachPart.setDisposition(Part.ATTACHMENT);

Use Java Gmail API to send an email with multiple (large) attachments

It turns out that my MimeMessage was generated correctly, however, if the attachments included in the MimeMessage are larger than 5MB, you need to use a different Gmail API send() method. The API docs are incredibly confusing because they appear to state that you need to make multiple calls to rest endpoints to upload multiple files. It turns out that the Gmail Java Api does all the for you based off the MimeMessage submitted.

Below is a code snippet that shows how to use the two methods: "simple upload" and "multipart upload".

com.google.api.services.gmailGmail service = (... defined above ...)
javax.mail.internet.MimeMessage message = (... defined above with attachments embedded ...)

/**
* Send email using Gmail API - dynamically uses simple or multipart send depending on attachments size
*
* @param mimeMessage MimeMessage (includes any attachments for the email)
* @param attachments the Set of files that were included in the MimeMessage (if any). Only used to calculate total size to see if we should use "simple" send or need to use multipart upload.
*/
void send(MimeMessage mimeMessage, @Nullable Set<File> attachments) throws Exception {

Message message = new Message();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
mimeMessage.writeTo(buffer);

// See if we need to use multipart upload
if (attachments!=null && computeTotalSizeOfAttachments(attachments) > BYTES_5MB) {

ByteArrayContent content = new ByteArrayContent("message/rfc822", buffer.toByteArray());
message = service.users().messages().send("me", null, content).execute();

// Otherwise, use "simple" send
} else {

String encodedEmail = Base64.encodeBase64URLSafeString(buffer.toByteArray());
message.setRaw(encodedEmail);
message = service.users().messages().send("me", message).execute();
}

System.out.println("Gmail Message: " + message.toPrettyString());
}


Related Topics



Leave a reply



Submit