/**
* 发送接口
* @param email 收件人
* @param text 正文内容
* @param subject 标题
* @param mailHost 邮件服务器地址
* @param mailPort 邮件端口
* @param mainForm 邮件发件人
* @param mainFormName 邮件来源
* @return 结果
*/
public boolean getMailSender(String email,String text,String subject,String mailHost,String mailPort,
String mainForm,String mainFormName) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailHost);
mailSender.setPort(Integer.valueOf(mailPort));
SimpleMailMessage mail = new SimpleMailMessage();
String[] t = email.split(",");
mail.setTo(t);
mail.setSubject(subject);
String nick = "";
try {
nick = MimeUtility.encodeText(mainFormName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
log.error("设置发件人呢称异常1========="+e);
}
try {
mail.setFrom(new InternetAddress(nick+" <"+mainForm+">").toString());
} catch (AddressException e) {
e.printStackTrace();
log.error("设置发件人呢称异常2========="+e);
}
mail.setSentDate(new Date());
mail.setText(text);
Mail mailExt=new Mail();
mailExt.setBaseMail(mail);
mailExt.setMailType(Mail.MAIL_TYPE_HTML);
try {
sendMail(mailSender,mailExt);
System.out.println("*****邮件发送成功*****");
return true;
} catch (Exception e1) {
e1.printStackTrace();
return false;
}
}
/**
*
* 方法说明:
* @param mail 邮件信息
* @param mailSender 邮件
*/
public void sendMail(JavaMailSenderImpl mailSender,Mail mail){
if(mailSender==null || mail==null){
try {
throw new Exception("没有指定邮件服务器或者邮件为空!");
} catch (Exception e) {
e.printStackTrace();
}
}
MimeMessage mailMessage = mailSender.createMimeMessage();
try {
SimpleMailMessage simpleMailMessage=mail.getBaseMail();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"UTF-8");
if(simpleMailMessage.getBcc()!=null){
messageHelper.setBcc(simpleMailMessage.getBcc());
}
if(simpleMailMessage.getCc()!=null){
messageHelper.setCc(simpleMailMessage.getCc());
}
if(simpleMailMessage.getFrom()!=null){
messageHelper.setFrom(simpleMailMessage.getFrom());
}
if(simpleMailMessage.getReplyTo()!=null){
messageHelper.setReplyTo(simpleMailMessage.getReplyTo());
}
if(simpleMailMessage.getSentDate()!=null){
messageHelper.setSentDate(simpleMailMessage.getSentDate());
}
if(simpleMailMessage.getSubject()!=null){
messageHelper.setSubject(simpleMailMessage.getSubject());
}
if(simpleMailMessage.getText()!=null){
messageHelper.setText(simpleMailMessage.getText());
}
if(simpleMailMessage.getTo()!=null){
messageHelper.setTo(simpleMailMessage.getTo());
}
//邮件内容,邮件类型html格式
messageHelper.setText(simpleMailMessage.getText(),Mail.MAIL_TYPE_HTML.equals(mail.getMailType()));
//添加附件
// List<File> files=mail.getAttachFiles();
// if(files!=null){
// for(File file:files){
// messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
// }
// }
} catch (Exception e) {
log.error("邮件报文出错",e);
}
mailSender.send(mailMessage);
}
Java实现发送邮件
最新推荐文章于 2021-08-09 23:44:45 发布