Search code examples
javajakarta-mailinputstreamemail-attachmentsjava1.4

Sending Emails in java


I am trying to send email this way but i could not figure out few things

  1. How do i use Input Stream object and add as a attachment.
  2. How to send multiple attachments
  3. How to send Multiple Attachments with HTML body

I tried below code and i could only send one attachment or HTML body

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
        new InternetAddress(to));

message.addRecipient(Message.RecipientType.CC,
        new InternetAddress(cc));
Address address[] =
        {new InternetAddress(replyTo)};
message.setReplyTo(address);
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
MimeBodyPart messageBodyPart = new MimeBodyPart();

Multipart multipart = new MimeMultipart();

messageBodyPart = new MimeBodyPart();
String file = "/file.pdf";
String fileName = "attachmentName";

DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setContent(body, "text/html");
// Send message
Transport.send(message);

Solution

  • This answers 1 question

    User ByteArrayDataSource it does have consutructor
    public ByteArrayDataSource(InputStream is, String type)

    This answers 2 question of your list.

    You can add multiple MimeBodyPart objects to Multipart Object

    This is code taken from Multipart.java it adds MimeBodyPart objects to vector

    public synchronized void addBodyPart(BodyPart part) throws MessagingException {
        if (parts == null) {
            parts = new Vector();
            parts.addElement(part);
            part.setParent(this);
        }
    }