新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
package email;
网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、微信小程序、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了孝义免费建站欢迎大家使用!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.BASE64Encoder;
public class Mail {
private static final String LINE_END = "\r\n";
private boolean isDebug = true;
private boolean isAllowReadSocketInfo = true;
private String host;
private String from;
private ListString to;
private ListString cc;
private ListString bcc;
private String subject;
private String user;
private String password;
private String contentType;
private String boundary;
private String boundaryNextPart;
private String contentTransferEncoding;
private String charset;
private String contentDisposition;
private String content;
private String simpleDatePattern;
private String defaultAttachmentContentType;
private ListMailPart partSet;
private static MapString, String contentTypeMap;
static {
// MIME Media Types
contentTypeMap = new HashMapString, String();
contentTypeMap.put("xls", "application/vnd.ms-excel");
contentTypeMap.put("xlsx", "application/vnd.ms-excel");
contentTypeMap.put("xlsm", "application/vnd.ms-excel");
contentTypeMap.put("xlsb", "application/vnd.ms-excel");
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
contentTypeMap.put("docm", "application/msword");
contentTypeMap.put("dotm", "application/msword");
}
private class MailPart extends Mail {
public MailPart() {
}
}
public Mail() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis();
boundaryNextPart = "--" + boundary;
contentTransferEncoding = "base64";
contentType = "multipart/alternative";
charset = Charset.defaultCharset().name();
partSet = new ArrayListMailPart();
to = new ArrayListString();
cc = new ArrayListString();
bcc = new ArrayListString();
}
private String getPartContentType(String fileName) {
String ret = null;
if (null != fileName) {
int flag = fileName.lastIndexOf(".");
if (0 = flag flag fileName.length() - 1) {
fileName = fileName.substring(flag + 1);
}
ret = contentTypeMap.get(fileName);
}
if (null == ret) {
ret = defaultAttachmentContentType;
}
return ret;
}
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "";
}
private String toBase64(byte[] bs) {
return new BASE64Encoder().encode(bs);
}
private String toBase64(String str) {
return toBase64(str, Charset.defaultCharset().name());
}
private String getAllParts() {
int partCount = partSet.size();
StringBuilder sbd = new StringBuilder(LINE_END);
for (int i = partCount - 1; i = 0; i--) {
Mail attachment = partSet.get(i);
String attachmentContent = attachment.getContent();
if (null != attachmentContent 0 attachmentContent.length()) {
sbd.append(getBoundaryNextPart()).append(LINE_END);
sbd.append("Content-Type: ");
sbd.append(attachment.getContentType());
sbd.append(LINE_END);
sbd.append("Content-Transfer-Encoding: ");
sbd.append(attachment.getContentTransferEncoding());
sbd.append(LINE_END);
if (i != partCount - 1) {
sbd.append("Content-Disposition: ");
sbd.append(attachment.getContentDisposition());
sbd.append(LINE_END);
}
sbd.append(LINE_END);
sbd.append(attachment.getContent());
sbd.append(LINE_END);
}
}
sbd.append(LINE_END);
sbd.append(LINE_END);
partSet.clear();
return sbd.toString();
}
private void addContent() {
if (null != content) {
MailPart part = new MailPart();
part.setContent(toBase64(content));
part.setContentType("text/plain;charset=\"" + charset + "\"");
partSet.add(part);
}
}
private String listToMailString(ListString mailAddressList) {
StringBuilder sbd = new StringBuilder();
if (null != mailAddressList) {
int listSize = mailAddressList.size();
for (int i = 0; i listSize; i++) {
if (0 != i) {
sbd.append(";");
}
sbd.append("").append(mailAddressList.get(i)).append("");
}
}
return sbd.toString();
}
private ListString getrecipient() {
ListString list = new ArrayListString();
list.addAll(to);
list.addAll(cc);
list.addAll(bcc);
return list;
}
public void addAttachment(String filePath) {
addAttachment(filePath, null);
}
public void addTo(String mailAddress) {
this.to.add(mailAddress);
}
public void addCc(String mailAddress) {
this.cc.add(mailAddress);
}
public void addBcc(String mailAddress) {
this.bcc.add(mailAddress);
}
public void addAttachment(String filePath, String charset) {
if (null != filePath filePath.length() 0) {
File file = new File(filePath);
try {
addAttachment(file.getName(), new FileInputStream(file),
charset);
} catch (FileNotFoundException e) {
System.out.println("错误:" + e.getMessage());
System.exit(1);
}
}
}
SmartUpload上传图片
记得下载jar包啊
别忘了把名改成smartUpload.jar
Utility类:
package com.tidyinfo.utils;
import java.util.Calendar;
public class Utility {
//生成形如:\2006\08\18的路径
private String path;
//生成形如: 20060818125012的唯一id号
private String id;
//生成形如:/2006/08/18的路径
private String url;
private String hour;
private String year;
private String month;
private String day;
private String minate;
private String second;
/** Creates a new instance of Utility */
public Utility() {
this.year =new Integer(Calendar.getInstance().get(Calendar.YEAR)).toString();
this.month = parseToString(Calendar.getInstance().get(Calendar.MONTH)+1);
this.day = parseToString(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
this.hour = parseToString(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
this.minate = parseToString(Calendar.getInstance().get(Calendar.MINUTE));
this.second = parseToString(Calendar.getInstance().get(Calendar.SECOND));
this.setId();
this.setPath();
this.setUrl();
}
protected String parseToString(int i){
return i10?("0"+i):new Integer(i).toString();
}
public String getId(){
return this.id;
}
public String getPath(){
return this.path;
}
public String getUrl(){
return this.url;
}
protected void setId(){
this.id = this.year+this.month+this.day+this.hour+this.minate+this.second;
}
protected void setPath(){
this.path = "\\"+this.year + "\\" + this.month + "\\" +
this.day ;
}
protected void setUrl(){
this.url = this.path.replace('\\','/');
}
}
Action:(根据不同情况要更改相关代码)
User userForm = new User();
String result = new String();
SmartUpload su = new SmartUpload();
//文件名
String filename = new String();
//文件扩展名
String fileext = new String();
//文件上传后存储的路径
String path = request.getRealPath(request.getContextPath());
path = path.substring(0,path.lastIndexOf("\\"));
path += "\\images";
//图片的url
String url = new String();
//创建文件夹
java.io.File file = new java.io.File(path);
file.mkdirs();
try{
// 上传初始化
su.initialize(this.servlet.getServletConfig(),request,response);
//设定上传限制
//1.限制每个上传照片的最大长度。
su.setMaxFileSize(5000000);
//2.限制总上传数据的长度。
su.setTotalMaxFileSize(10000000);
//3.设定允许上传的照片(通过扩展名限制)。
su.setAllowedFilesList("jpg,gif,GIF,JPG");
//上传照片
su.upload();
//获得请求的表单数据
String username = su.getRequest().getParameter("username");//username
String password = su.getRequest().getParameter("password");//password
String sex = su.getRequest().getParameter("sex");//sex
String email =su.getRequest().getParameter("email");//email
String apwd =su.getRequest().getParameter("apwd");//question of password
String rpwd =su.getRequest().getParameter("rpwd");//anser of password
userForm.setUsername(username);
userForm.setPassword(password);
userForm.setSex(sex);
userForm.setEmail(email);
userForm.setApwd(apwd);
userForm.setRpwd(rpwd);
//将上传照片全部保存到指定目录
if(!su.getFiles().getFile(0).isMissing()){
su.save(path,su.SAVE_PHYSICAL);
//文件名
filename = su.getFiles().getFile(0).getFileName();
//得到扩展名
fileext = su.getFiles().getFile(0).getFileExt();
//给图片改名,命名形如:20060814135411.gif
Utility u = new Utility();
String newName = u.getId()+"."+fileext;
java.io.File oldFile = new java.io.File(path+"\\"+filename);
java.io.File newFile = new java.io.File( path + "\\"+newName);
//上传图片的url
url = request.getContextPath()+"/images/"+newName;
if(oldFile!=null){
oldFile.renameTo(newFile);
}else{
result+="命名出错!";
}
System.out.println("0000000000000000000"+filename);
System.out.println("0000000000000000000"+path+"\\"+newName);
System.out.println("0000000000000000000"+url);
System.out.println(result);
}
}catch(com.jspsmart.upload.SmartUploadException e){
result += "file出错信息:";
result += e.getMessage();
System.out.println(result);
}
实现java发送邮件的过程大体有以下几步:
准备一个properties文件,该文件中存放SMTP服务器地址等参数。
利用properties创建一个Session对象
利用Session创建Message对象,然后设置邮件主题和正文
利用Transport对象发送邮件
需要的jar有2个:activation.jar和mail.jar发送附件,需要用到Multipart对象。
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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.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;
import javax.mail.internet.MimeUtility;
public class JavaMailWithAttachment {
private MimeMessage message;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private Properties properties = new Properties();
/*
* 初始化方法
*/
public JavaMailWithAttachment(boolean debug) {
InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");
try {
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
} catch (IOException e) {
e.printStackTrace();
}
session = Session.getInstance(properties);
session.setDebug(debug);// 开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
* @param attachment
* 附件
*/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
// 收件人
InternetAddress to = new InternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO, to);
// 邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
JavaMailWithAttachment se = new JavaMailWithAttachment(true);
File affix = new File("c:\\测试-test.txt");
se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);//
}
}
int id = (Integer) request.getSession().getAttribute("id");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setFileSizeMax(1024 * 1024);//1M
ListFileItem items = sfu.parseRequest(request);
for (int i = 0; i items.size(); i++) {
FileItem item = items.get(i);
if (!item.isFormField()) {
ServletContext sctx = getServletContext();
String picurl = sctx.getRealPath("upload");
String fileName = item.getName();
fileName = fileName.substring(fileName
.lastIndexOf("\\") + 1);
PicDao picDao = new PicDaoImpl();
System.err.println(id);
picDao.savePic(id, fileName);
File file = new File(picurl + "/pic_"
+ StringUtils.leftPad(id + "", 5, '0') + "/"
+ fileName);
item.write(file);
}
}
response.sendRedirect("userDetail.do?id=" + id);