Ví dụ gửi email có file đính kèm từ máy của bạn:
Ví dụ
<%@ page import = "java.io.*,java.util.*,javax.mail.*" %>
<%@ page import = "javax.mail.internet.*,javax.activation.*" %>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%
String result;
String to = "abcd@gmail.com";
String from = "mcmohd@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("This is the Subject Line!");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
result = "Sent message successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send message....";
}
%>
<html>
<head> <title>Send Attachment Email using JSP</title> </head>
<body>
<center> <h1>Send Attachment Email using JSP</h1> </center>
<p align="center"> <% out.println("Result: " + result + "\n"); %> </p>
</body>
</html>
Phần xác thực người dùng
Nếu server email yêu cầu user/password xác thực, set properties:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");