Java Mail API
public static sendMail() {
//sending email using java code using javax.mail api
Properties props = new Properties();
props.put("mail.smtp.host", "MailHost");
props.put("mail.smtp.port", "MailHostPort");
props.put("mail.smtp.auth", "true");
final String user = "EmailUsername";
final String password = "Password";
String to = "EmailToAddress";
String from = "EmailFromAddress";
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,to);
message.setSubject("Mail Subject any text");
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent("mail content in html fromat or text", "text/html");
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource source1= new FileDataSource(new File("attachment path if required"));
messageBodyPart2.setDataHandler(new DataHandler(source1));
messageBodyPart2.setFileName(doctitle);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart2);
multipart.addBodyPart(messageBodyPart1);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
No comments:
Post a Comment