首页 > 代码库 > java通过springMail发送邮件
java通过springMail发送邮件
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=smtpmail.from=*@*.commail.host=smtp.*.commail.port=25mail.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(); } }
java通过springMail发送邮件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。