Sending Mail Attachment Using Java

Sending an email with an attachment using javamail API

  1. Disable Your Anti Virus

because you have some warning like this

warning message form antivirus

Try this code... It Help You....

public class SendMail {
public SendMail() throws MessagingException {
String host = "smtp.gmail.com";
String Password = "............";
String from = "XXXXXXXXXX@gmail.com";
String toAddress = "YYYYYYYYYYYYY@gmail.com";
String filename = "C:/SendAttachment.java";
// 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);
}
}
public static void main(String args[]){
try {
SendMail sm = new SendMail();
} catch (MessagingException ex) {
Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Java send email with file in attachment

Your code is wrong. If you copied it from somewhere, the original is wrong too, or you copied it wrong. This is what you want:

    Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("email0@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email0@gmail.com"));
message.setSubject("Attach file Test from Netbeans");

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("PFA");

attachmentBodyPart = new MimeBodyPart();

System.out.println("The filetosend is ="+filetosend);
System.out.println("The source is ="+source);

attachmentBodyPart.attachFile(filetosend);
System.out.println("The file name is ="+attachmentBodyPart.getFileName());

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);

message.setContent(multipart);
System.out.println("The message multi part is ="+multipart);

System.out.println("Sending");

Transport.send(message);

How to send any type of attachment using java mail api?

It turns out that a ByteArrayDataSource can be used to send a stream of any type. You will need to specify the mime type in addition to the stream as there is no way it can know the type without it. If the InputStream represents a jpeg image, you would use "image/jpeg" as the type passed to ByteArrayDataSource.

Know that ByteArrayDataSource will completely read the InputStream into a byte array for processing. If the InputStream is very large, that could consume a large amount of memory. Then again, most email systems limit attachment size.

Please note that this code is not production ready and requires error / exception handling.

    messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
//
// FileInputStream is just for the example. You can use other InputStreams as well.
//
InputStream inputStream = new FileInputStream(filename);

DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "text/plain;charset=UTF-8");
}
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts
message.setContent(multipart);

[EDIT] Here is some code to test that your InputStream has data. You can call it with the source above to print out the number of bytes in your input stream.

private static void printDataSourceByteCount(DataSource source) throws IOException {
try (InputStream is = source.getInputStream()) {

long totalBytesRead = 0;
byte [] buffer = new byte[2048];
int bytesRead = is.read(buffer);
while(bytesRead > 0) {
totalBytesRead += bytesRead;
bytesRead = is.read(buffer);
}
System.out.println(String.format("Read %d bytes", totalBytesRead));
}
}

[EDIT] And here is my fully functioning example that uses a test pdf. A text file works as well as long as you change the mime type to "text/plain".

public static void main(String[] args) {

// Recipient's email ID needs to be mentioned.
String to = "<to email>";

// Sender's email ID needs to be mentioned
String from = "<from email>";

final String username = "<email server username>";// change accordingly
final String password = "<email server password>";// change accordingly

// Set to your email server
String host = "mail.acme.com";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");

// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

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("Testing Subject");

// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();

// Now set the actual message
messageBodyPart.setText("Hello. Attached is a very important PDF.");

// Create a multipar message
Multipart multipart = new MimeMultipart();

// Set text message part
multipart.addBodyPart(messageBodyPart);

// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/Users/rick/Tmp/test.pdf";

DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "application/pdf");
}

printDataSourceByteCount(source);

messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("SecretsOfTheUniverse.pdf");
multipart.addBodyPart(messageBodyPart);

// Send the complete message parts
message.setContent(multipart);

// Send message
Transport.send(message);

System.out.println("Sent message successfully....");

} catch (MessagingException e) {
// TODO handle the error
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO handle the error
e.printStackTrace();
} catch (IOException e) {
// TODO handle the error
e.printStackTrace();
}
}

How to add attachment to my mail sender JavaMail?

I got it !
I look at the MimeMessage documentation and found the solution, you just have to change the content inside of the try (in SendMail.java) to this :

        MimeMessage mimeMessage = new MimeMessage(session);

MimeMultipart mimeMultipart = new MimeMultipart();

MimeBodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setContent(message, "text/plain; charset=UTF-8");

mimeMultipart.addBodyPart(messageBodyPart);

MimeBodyPart attachmentBodyPart = new MimeBodyPart();

String filename = "path to your file, exemple : /storage/path.txt" ;
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(filename);

mimeMultipart.addBodyPart(attachmentBodyPart);

mimeMessage.setFrom(new InternetAddress(Config.MAIL_SENDER));

mimeMessage.addRecipient(Message.RecipientType.TO, new
InternetAddress(Config.MAIL_RECEIVER));

mimeMessage.setSubject(subject);

mimeMessage.setContent(mimeMultipart);

Transport.send(mimeMessage);

I also changed the names of instances I used.

how to send a html email with attached file using JavaMail

Creating a mail with an HTML body and an attachment, actually means creating a mail whose content is a "multipart entity", that contains two parts, one of them being the HTML content, et the second being the attached file.

This does not correspond to your current code:

Multipart multipart = new MimeMultipart(); // creating a multipart is OK

// Creating the first body part of the multipart, it's OK
messageBodyPart = new MimeBodyPart();
// ... bla bla
// ok, so this body part is the "attachment file"
messageBodyPart.setDataHandler(new DataHandler(source));
// ... bla bla
multipart.addBodyPart(messageBodyPart); // at this point, the multipart contains your file attachment, but only that!

// at this point, you set your mail's body to be the HTML message
message.setContent(html, "text/html; charset=utf-8");
// and then right after that, you **reset** your mail's content to be your multipart, which does not contain the HTML
message.setContent(multipart);

At this point, your email's content is a multipart that has only 1 part, which is your attachment.

So, to reach your expected result, you should proceed differently :

  1. Create a multipart (as you did)
  2. Create a part, that has your file attachment as a content (as you did)
  3. Add this first part to the multipart (as you did)
  4. Create a second MimeBodyPart
  5. Add your html content to that second part
  6. Add this second part to your multipart
  7. Set your email's content to be the multipart (as you did)

Which roughly translates to :

Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource)); //2
attachmentBodyPart.setFileName(file.getName()); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent(htmlMessageAsString , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7


Related Topics



Leave a reply



Submit