主要代码:
private class SendMailThread implements Runnable{
private Message msg;
private Integer[] userIds;
private AttachDto ad;
private String[] newNames;
private String realPath;
private UserEmail ue;
public SendMailThread(UserEmail ue,Message msg, Integer[] userIds, AttachDto ad,String[] newNames,String realPath) {
super();
this.msg = msg;
this.userIds = userIds;
this.ad = ad;
this.newNames=newNames;
this.realPath = realPath;
this.ue = ue;
}
@Override
public void run() {
sendMail(ue,msg,userIds,ad,newNames,realPath);
}
}
private void sendMail(UserEmail ue,Message msg, Integer[] userIds, AttachDto ad,String[] newNames,String realPath) {
try {
System.out.println("邮件开始发送");
JavaMailSenderImpl jms = (JavaMailSenderImpl)mailSender;
jms.setHost(ue.getHost());
jms.setPassword(ue.getPassword());
jms.setProtocol(ue.getProtocol());
jms.setUsername(ue.getUsername());
MimeMessage email = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(email,true,"utf-8");
helper.setFrom(ue.getUser().getEmail());
helper.setSubject(msg.getTitle());
List<String> mailTos = userDao.listAllSendEmail(userIds);
for(String mail:mailTos){
helper.addTo(mail);
}
String uploadPath = ad.getUploadPath();
if(ad.isHasAttach()){
File[] atts = ad.getAtts();
String[] filenames = ad.getAttsFilename();
for(int i=0;i<atts.length;i++){
String fn = filenames[i];
helper.addAttachment(MimeUtility.encodeText(fn), new FileSystemResource(uploadPath+"/"+newNames[i]));
}
}
String content = msg.getContent();
Map<String,String> imgMaps = new HashMap<String,String>();
List<String> imgs = listContentImgUrl(content);
int i=0;
for(String img:imgs){
imgMaps.put("x"+i, img);
content = content.replace(img, "cid:"+("x"+i));
i++;
}
helper.setText(content,true);
Set<String> keys = imgMaps.keySet();
for(String key:keys){
String url = imgMaps.get(key);
if(url.startsWith("http://")){
helper.addInline(key,new URLDataSource(new URL(url)));
}else{
String path = realPath.replace("upload", "")+url;
helper.addInline(key, new FileSystemResource(path));
}
}
jms.send(email);
System.out.println("邮件发送成功");
} catch (MailException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public void add(Message msg, Integer[] userIds,AttachDto ad,int isEmail) throws IOException {
msg.setUser(SystemContext.getLoginUser());
msg.setCreateDate(new Date());
this.messageDao.add(msg);
UserMessage um = null;
List<User> users = this.userDao.listByIds(userIds);
for(User u:users){
um = new UserMessage();
um.setIsRead(0);
um.setMessage(msg);
um.setUser(u);
messageDao.addObj(um);
}
String[] newNames = DocumentUtil.addAttach(ad, attachmentDao, msg, null);
if(isEmail>0){
UserEmail ue = this.userDao.loadUserEmail(SystemContext.getLoginUser().getId());
taskExecutor.execute(new SendMailThread(ue,msg, userIds, ad,newNames,SystemContext.getRealPath()));
}
}