protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String sendMan = request.getParameter("sendMan");//发送人
String haveMan = request.getParameter("haveMan");//接收人,多者用,分割
String haveTitle = request.getParameter("haveTitle");//标题
String havecontext = request.getParameter("havecontext");//内容
String haveimg = request.getParameter("haveimg");//附件图片
String havefj = request.getParameter("havefj");//附件文本
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.host", "smtp.gmail.com");//邮件服务器为GMail
props.setProperty("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username",
"password");
}
});
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(sendMan));
message.setSubject(haveTitle);
message.setRecipients(RecipientType.TO, InternetAddress
.parse(haveMan));//群发
MimeMultipart msgMultipart = new MimeMultipart("mixed");//mixed是一种形式,包含附件与邮件本体的并行结构
message.setContent(msgMultipart);
MimeBodyPart havefjPart = new MimeBodyPart();
MimeBodyPart haveimgPart = new MimeBodyPart();
msgMultipart.addBodyPart(havefjPart);
msgMultipart.addBodyPart(haveimgPart);
DataSource ds1 = new FileDataSource(havefj);
DataHandler dh1 = new DataHandler(ds1 ); //需要引入activation.jar
havefjPart.setDataHandler(dh1);
havefjPart.setFileName(
MimeUtility.encodeText("fijian1.txt") //设置附件文件名称
);
DataSource ds2 = new FileDataSource(
haveimg
);
DataHandler dh2 = new DataHandler(ds2 );
haveimgPart.setDataHandler(dh2);
haveimgPart.setFileName("logo.gif");
MimeMultipart bodyMultipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
bodyMultipart.addBodyPart(htmlPart);
htmlPart.setContent(havecontext,
"text/html;charset=gbk");
message.saveChanges();//生成邮件
Transport.send(message);//发送
request.getRequestDispatcher("/success.jsp").forward(request,
response);
} catch (AddressException e) {
e.printStackTrace();
request.getRequestDispatcher("/failed.jsp").forward(request,
response);
} catch (MessagingException e) {
e.printStackTrace();
request.getRequestDispatcher("/failed.jsp").forward(request,
response);
}
}
JavaMail发送邮件具有附件功能
最新推荐文章于 2024-04-29 14:45:34 发布