import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "mugihnf@gmail.com";
final String password = "13061975";
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.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
//pengirim
message.setFrom(new InternetAddress("mugihnf@gmail.com"));
//penerima
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mugihnf@gmail.com,dev_kpp@yahoo.com"));
message.setSubject("Testing Subject2");
// message.setText("Dear Mail Crawler,"+ "\n\n No spam to my email, please!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("hi inii adalah bagian dari bofy dari mail\n\n bari ke dua\n\n baris ketiga");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String dir = "C:\\Users\\Public\\Pictures\\Sample Pictures\\"; //lokasi direktori
String filename = "Koala.jpg";
DataSource source = new FileDataSource(dir+filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}