使用Spring JavaMailSenderImpl发送邮件报错:
详细信息:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. u12sm73042tia.38 at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:879) at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:599) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:319) at com.roadway.edmail.util.JMail2.sendMail(JMail2.java:278) at com.roadway.edmail.bo.feedback.FeedbackSender.sender(FeedbackSender.java:72) at org.apache.jsp.test_jsp._jspService(test_jsp.java:59) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
原因是用gmail邮件进行发送,需要添加一下参数:
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.port", "465"); properties.setProperty("mail.smtp.socketFactory.port", "465");
发送Mail实例代码
//检测收件地址合法性 if(toAry == null || toAry.length == 0 || toAry[0] == null || "".equals(toAry[0])){ if(this.logger.isErrorEnabled()){ this.logger.error("Recipient found empty while sending a mail,Mail subject is : " + mailSubject); } return "Recipient is empty"; } JavaMailSenderImpl javaMailSender = (JavaMailSenderImpl)AppUtil.getBean("mailSender"); //检测是否为smtp.gmail.com if(javaMailSender.getHost().indexOf("smtp.gmail.com") >=0 ){ Properties properties = javaMailSender.getJavaMailProperties(); properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.port", "465"); properties.setProperty("mail.smtp.socketFactory.port", "465"); javaMailSender.setJavaMailProperties(properties); } MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, fileAry != null); //设置发送者 mimeMessageHelper.setFrom(from == null ? this.defaultFrom : from); //设置接受者 mimeMessageHelper.setTo(toAry); //设置抄送者 if(cc != null && !"".equals(cc)) mimeMessageHelper.setCc(cc); //设置回复者 if(replyTo != null && !"".equals(replyTo)) mimeMessageHelper.setReplyTo(replyTo); //邮件主题 mimeMessageHelper.setSubject(mailSubject); //邮件正文 mimeMessageHelper.setText(templateStr,true); //判断资源文件列表是否为空 if(fileAry != null){ if(flag){//若为嵌入式资源 for(int i = 0; i < fileAry.length; i++) mimeMessageHelper.addInline(stringAry[i], fileAry[i]); }else{ for(int i = 0; i < fileAry.length; i++) mimeMessageHelper.addAttachment(stringAry[i], fileAry[i]); } } //发送 javaMailSender.send(mimeMessage);