为什么后台用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);
        }
    }
}

java tomcat vps email 部署

Cassius 11 years, 5 months ago

问题已经解决了,是缺少了mail相关的配置文件

街头0流氓 answered 11 years, 5 months ago

Your Answer