1,首先在spring配置文件中加入邮件发送配置
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="protocol" value="${mail.protocol}"/> <property name="host" value="${mail.host}"/> <property name="port" value="${mail.port}" /> <property name="username" value="${mail.username}"/> <property name="password" value="${mail.password}"/> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> </props> </property> </bean>
2,配置中的参数可以写在properties配置文件中
mail.protocol=smtp mail.from=*@*.com mail.host=smtp.*.com mail.port=25 mail.username= mail.password=
3,java中的代码
首先可以定义一个通用的邮件bean
import java.io.Serializable; import org.springframework.web.multipart.MultipartFile; public class Email implements Serializable { private static final long serialVersionUID = 1L; /** 发件人 **/ private String sender; /** 收件人* */ private String[] address; /** 抄送给* */ private String[] cc; /** 暗送给* */ private String[] bcc; /** 回复给* */ private String replyTo; /** 邮件主题* */ private String subject;/** 邮件内容*/ private String content; /** 附件* */ private MultipartFile[] attachment = new MultipartFile[0]; //////////////////////////getters & setters////////////////////////////// }
发送代码
@Resource(name = "mailSender") private JavaMailSender mailSender; public void sendMailBySynchronizationMode(Email email) { MimeMessage mime = mailSender.createMimeMessage(); MimeMessageHelper helper; String content = email.getContent(); try { helper = new MimeMessageHelper(mime, true, "utf-8"); helper.setFrom(email.getSender());//发件人 helper.setTo(email.getAddress());//收件人 if (CommonUtils.isNotEmpty(email.getCc())) { helper.setCc(email.getCc());// 抄送 } if (CommonUtils.isNotEmpty(email.getBcc())) { helper.setBcc(email.getBcc());// 暗送 } if (CommonUtils.isNotEmpty(email.getReplyTo())) { helper.setReplyTo(email.getReplyTo());// 回复到 } helper.setSubject(email.getSubject());//邮件主题 helper.setText(content, true);//true表示设定html格式 //处理附件 for (MultipartFile file : email.getAttachment()) { if (file == null || file.isEmpty()) { continue; } String fileName = file.getOriginalFilename(); try { fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1"); } catch (Exception e) { } helper.addAttachment(fileName, new ByteArrayResource(file.getBytes())); } mailSender.send(mime); } catch (Exception e) { e.printStackTrace(); } }
时间: 2024-12-06 11:50:08