开发者社区> 问答> 正文

为什么后台用Java发邮件,在本地可以,部署到vps上就不行了?

本地ubuntu , vps是centOS
到底是哪里出问题了呢?
试了456端口和25端口都不行……服务器是tomcat
另,服务器上用Python写脚本是可以发邮件的= =!

package util;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender {

    public void postMail(String recipients[], String subject, String text) {
        // Set the host smtp address
        ResourceBundle rb = ResourceBundle.getBundle("mail");
        String host = rb.getString("smtp");
        int port = 25;
        String from = rb.getString("from");
        // Get system properties
        Properties props = new Properties();
        // Setup mail server
        props.setProperty("mail.smtp.host", host);
         props.put("mail.smtp.auth","true");
         props.put("mail.smtp.port", port);
        // Get the default Session object.props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        ResourceBundle rb = ResourceBundle.getBundle("mail");
                        String username = rb.getString("username");
                        String password = rb.getString("password");
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set the RFC 822 "From" header field using the
            // value of the InternetAddress.getLocalAddress method.
            message.setFrom(new InternetAddress(from));

            // Add the given addresses to the specified recipient type.
            StringBuilder sb = new StringBuilder();
            for (String s : recipients) {
                sb.append(" ");
                sb.append(s);
            }
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(sb.toString()));

            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(sb.toString()));
            message.setSubject(MimeUtility.encodeText(subject));
            message.setContent(text, "text/html;charset=utf8");
            Date date = new Date();
            message.setSentDate(date);

            Transport.send(message);

            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
            LogDetail.logexception(e);

展开
收起
小旋风柴进 2016-02-29 15:07:38 3520 0
1 条回答
写回答
取消 提交回答
  • 是缺少了mail相关的配置文件

    2019-07-17 18:50:20
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载