赞
踩
在部署项目到阿里的ECS服务器上的时候,发现邮件无法发送,报出异常
原代码:
- public static void sendMail(String to,String code){
-
- try {
- // 获得连接:
- Properties props = new Properties(new InputStream);
- //用于发送邮件的邮箱账号密码
- props.put("username", "username@163.com");
- props.put("password", "password");
- //smtp传输协议
- props.put("mail.transport.protocol", "smtp" );
- //网易邮箱的smtp服务器地址
- props.put("mail.smtp.host", "smtp.163.com");
- //smtp端口
- props.put("mail.smtp.port", "25" );
-
- Session defaultInstance = Session.getDefaultInstance(props);
- // 构建邮件:
- Message message = new MimeMessage(defaultInstance);
-
- message.setFrom(new InternetAddress("sendName@163.com"));
- // 设置收件人:
-
- // TO:收件人 CC:抄送 BCC:暗送,密送.
- message.addRecipient(RecipientType.TO, new InternetAddress(to));
- // 主题:
- message.setSubject("邮件主题");
- // 正文和响应头
- message.setContent("正文", "text/html;charset=UTF-8");
- // 发送邮件:
- message.saveChanges();
-
- Transport transport = defaultInstance.getTransport("smtp");
- transport.connect(props.getProperty("mail.smtp.host"),props.getProperty("username"),props.getProperty("password"));
- transport.sendMessage(message,message.getAllRecipients());
- transport.close();
-
- } catch (MessagingException e) {
- e.printStackTrace();
- }
- }
javax.mail.MessagingException: Could not connect to SMTP host: smtp.163.com, port: 25;
无法连接smtp.163.com和25端口
询问阿里云客服之后得知是为了防止垃圾邮件泛滥,关闭了25端口,并建议使用加密端口
由于加密端口使用的是ssl协议, 不能再使用上面的代码了
ssl协议需要加密的ssl连接,java提供了javax.net.ssl.SSLSocketFactory类,从类中获取加密的SSLSocket
代码:
- public static void sendMail(String to,String code) {
- Properties props = new Properties(new InputStream);
- props.put("username", "username@163.com");
- props.put("password", "password");
-
- //网易的smtp服务器地址
- props.put("mail.smtp.host", "smtp.163.com");
- //SSLSocketFactory类的端口
- props.put("mail.smtp.socketFactory.port", "465");
- //SSLSocketFactory类
- props.put("mail.smtp.socketFactory.class",
- "javax.net.ssl.SSLSocketFactory");
- props.put("mail.smtp.auth", "true");
- //网易提供的ssl加密端口,QQ邮箱也是该端口
- props.put("mail.smtp.port", "465");
-
- Session defaultInstance = Session.getDefaultInstance(props);
-
- try {
-
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("sendName@163.com"));
- message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
- message.setSubject("邮件标题");
- // 正文和响应头
- message.setContent("邮件主题", "text/html;charset=UTF-8");
- message.saveChanges();
- Transport transport = defaultInstance.getTransport("smtp");
- transport.connect(props.getProperty("mail.smtp.host"),props.getProperty("username"),props.getProperty("password"));
- transport.sendMessage(message,message.getAllRecipients());
- transport.close();
- } catch (MessagingException e) {throw new RuntimeException(e);}}
- 这样ssl加密协议的工具类就写好了,可以放在阿里云ecs服务端上成功运行了.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。