📄 sendattachmentmail.java
字号:
/*
* Created on 2004-6-26
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.mail;
import java.io.IOException;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author haoyulong
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class SendAttachmentMail extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//TODO Method stub generated by Lomboz
//变量声明
String smtp,from,to,cc,bcc,subject,body;
// 获得用户输入数据
smtp = "127.0.0.1";
from = request.getParameter("from");
to = request.getParameter("to");
subject = request.getParameter("subject");
if(subject!=null){
subject = new String(subject.getBytes("iso-8859-1"));
}
body = request.getParameter("body");
///////////////////////
java.util.Properties props;//系统属性
Session mailSession;//邮件会话对象
MimeMessage mimeMsg; //MIME邮件对象
try{
//设置系统属性
props = java.lang.System.getProperties(); //获得系统属性对象
props.put("mail.smtp.host",smtp); //设置SMTP主机
//获得邮件会话对象
mailSession = Session.getDefaultInstance(props,null);
//创建MIME邮件对象
mimeMsg = new MimeMessage(mailSession);
//设置发信人
mimeMsg.setFrom(new InternetAddress(from));
//设置收信人
if(to!=null)
{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
}
//设置邮件主题
mimeMsg.setSubject(subject,"gb2312");
//处理邮件体
// 正文部分
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
String contentMessage=request.getParameter("body");
messageBodyPart.setText(contentMessage);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
String filename=request.getParameter("thefile");
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
mimeMsg.setContent(multipart);
// Send the message
Transport.send(mimeMsg);
// 设置邮件内容,将邮件body部分转化为HTML格式
// mimeMsg.setDataHandler(new javax.activation.DataHandler(new StringDataSource (body,"text/html")));
//发送邮件
// Transport.send(mimeMsg);
}catch (Exception e){
response.getWriter().println(e.toString());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -