Logika Standar

Monday, 2 June 2014

kirim email dengan lampiran file ( attach file ) menggunakan java

Berikut merupakan contoh cara mengirim email menggunakan bahasa pemrograman java dengan melampirkan file pada saat mengirim email.

public static void kirimAttachmentEmail(Session session, String toEmail, String subject, String body){
    try{
         MimeMessage msg = new MimeMessage(session);
         msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
         msg.addHeader("format", "flowed");
         msg.addHeader("Content-Transfer-Encoding", "8bit");
          
         msg.setFrom(new InternetAddress("no_reply@journaldev.com", "NoReply-JD"));

         msg.setReplyTo(InternetAddress.parse("no_reply@journaldev.com", false));

         msg.setSubject(subject, "UTF-8");

         msg.setSentDate(new Date());

         msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
          
         // Create the message body part
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText(body);
         
         // Create a multipart message for attachment
         Multipart multipart = new MimeMultipart();

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

         // Second part is attachment
         messageBodyPart = new MimeBodyPart();
         String filename = "abc.txt";
         DataSource source = new FileDataSource(filename);
         messageBodyPart.setDataHandler(new DataHandler(source));
         messageBodyPart.setFileName(filename);
         multipart.addBodyPart(messageBodyPart);

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

         // Send message
         Transport.send(msg);
         System.out.println("EMail Sent Successfully with attachment!!");
      }catch (MessagingException e) {
         e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
    }
}