|
发表于 2018-6-17 01:29:33
|
显示全部楼层
广东省广州市
- public static void sendEmail(emailEntity record) {
- try{
- // 创建邮件配置
- Properties props = new Properties();
- props.setProperty("mail.transport.protocol", "smtp"); // 使用的协yi(JavaMail规范要求)
- props.setProperty("mail.smtp.host", "smtp.qq.com"); // 发件人的邮箱的 SMTP 服务器地址
- props.setProperty("mail.smtp.port", "465");
- props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
- props.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl
- // 根据邮件配置创建会话,注意session别导错包
- Session session = Session.getDefaultInstance(props);
- // 开启debug模式,可以看到更多详细的输入日志
- session.setDebug(false);
- //创建邮件
- MimeMessage msg = new MimeMessage(session);
- // address邮件地址, personal邮件昵称, charset编码方式
- InternetAddress fromAddress = new InternetAddress(record.getFromcode(),
- record.getAddressor(), "utf-8");
- // 设置发送邮件方
- msg.setFrom(fromAddress);
- InternetAddress receiveAddress = new InternetAddress(
- record.getTocode(), record.getRecipients(), "utf-8");
- // 设置邮件接收方
- msg.setRecipient(Message.RecipientType.TO, receiveAddress);
- // 设置邮件标题
- msg.setSubject(record.getSubject(), "utf-8");
- // 设置显示的发件时间
- msg.setSentDate(new Date());
- MimeMultipart mp = new MimeMultipart();
- BodyPart bp = new MimeBodyPart();
- bp.setContent(record.getContent(), "text/html;charset=utf-8");
- mp.addBodyPart(bp);
- if(!UtilString.isEmpty(record.getFileName())){
- bp = new MimeBodyPart();
- FileDataSource fds = new FileDataSource(record.getFileName());
- bp.setDataHandler(new DataHandler(fds));
- bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
- }
- mp.addBodyPart(bp);
- msg.setContent(mp);
- // 保存设置
- msg.saveChanges();
- //获取传输通道
- Transport transport = session.getTransport();
- transport.connect("smtp.qq.com",record.getFromcode(), record.getPassword());
- //连接,并发送邮件
- transport.sendMessage(msg, msg.getAllRecipients());
- transport.close();
- }catch(Exception e){
- if(e instanceof javax.mail.AuthenticationFailedException){
- throw new crmException("请检查发件人邮箱设置是否正确");
- }
- throw new crmException(e.getMessage());
- }
- }
复制代码
静态方法 也是之前的代码里面翻出来的 |
|