JavaMail - 设置端口、代理和防火墙

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19092938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:01:46  来源:igfitidea点击:

JavaMail - Setting up ports, proxy and firewall

javaproxyjavamailfirewallconnectexception

提问by DoTheGenes

I'm trying to make a very simple E-Mail application, and I have written a few lines of basic code. One exception I keep getting is com.sun.mail.util.MailConnectException. Is there a simple way to code my way through a proxy or a firewall without messing with the connectivity settings of the sending machine?

我正在尝试制作一个非常简单的电子邮件应用程序,我已经编写了几行基本代码。我不断收到的一个例外是com.sun.mail.util.MailConnectException. 有没有一种简单的方法可以通过代理或防火墙对我的方式进行编码,而不会弄乱发送机器的连接设置?

My code so far:

到目前为止我的代码:

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

public class SendHTMLMail {
public static void main(String[] args) {
    // Recipient ID needs to be set
    String to = "[email protected]";

    // Senders ID needs to be set
    String from = "[email protected]";

    // Assuming localhost
    String host = "localhost";

    // System properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

       //Get default session object
    Session session = Session.getDefaultInstance(properties);

    try {
        // Default MimeMessage object
        MimeMessage mMessage = new MimeMessage(session);

        // Set from
        mMessage.setFrom(new InternetAddress(from));

        // Set to
        mMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set subject
        mMessage.setSubject("This is the subject line");

        // Set the actual message
        mMessage.setContent("<h1>This is the actual message</h1>", "text/html");

        // SEND MESSAGE
        Transport.send(mMessage);
        System.out.println("Message sent...");
    }catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

采纳答案by Benny Bottema

There are a bunch of properties you need to set correctly in the right combination for proxies to work in JavaMail. And JavaMail only supports anonymous SOCKS proxies.

您需要在正确的组合中正确设置一堆属性,以便代理在 JavaMail 中工作。而JavaMail 只支持匿名 SOCKS 代理

Simple Java Mailhowever takes cares of these properties for you and adds authenticated proxy support on top of that. It's open source and still actively developed.

然而,Simple Java Mail会为您处理这些属性,并在此基础上添加经过身份验证的代理支持。它是开源的,并且仍在积极开发中。

Here's how your code would look with Simple Java Mail:

以下是您的代码在 Simple Java Mail 中的外观:

Mailer mailer = new Mailer(// note: from 5.0.0 on use MailerBuilder instead
        new ServerConfig("localhost", thePort, theUser, thePasswordd),
        TransportStrategy.SMTP_PLAIN,
        new ProxyConfig(proxyHost, proxyPort /*, proxyUser, proxyPassword */)
);

mailer.sendMail(new EmailBuilder()
        .from("mytest", "[email protected]")
        .to("test", "[email protected]")
        .subject("This is the subject line")
        .textHTML("<h1>This is the actual message</h1>")
        .build());

System.out.println("Message sent...");

A lotless code and very expressive.

一个很多更少的代码和极具表现力。

回答by RAlex

From the Oracle's JAVAMAIL API FAQ (http://www.oracle.com/technetwork/java/javamail/faq/index.htm):

来自 Oracle 的 JAVAMAIL API 常见问题解答 ( http://www.oracle.com/technetwork/java/javamail/faq/index.htm):

JavaMail does not currently support accessing mail servers through a web proxy server.

JavaMail 目前不支持通过 Web 代理服务器访问邮件服务器。

But:

但:

If your proxy server supports the SOCKS V4 or V5 protocol, and allows anonymous connections, and you're using JDK 1.5 or newer and JavaMail 1.4.5 or newer, you can configure a SOCKS proxy on a per-session, per-protocol basis by setting the "mail.smtp.socks.host" property as described in the javadocs for the com.sun.mail.smtp package.

如果您的代理服务器支持 SOCKS V4 或 V5 协议,并允许匿名连接,并且您使用的是 JDK 1.5 或更高版本和 JavaMail 1.4.5 或更高版本,您可以在每个会话、每个协议的基础上配置 SOCKS 代理通过设置“mail.smtp.socks.host”属性,如 com.sun.mail.smtp 包的 javadoc 中所述。

In order to use a SOCKS proxy, you have to set the mail.smtp.socks.hostand mail.smtp.socks.portparameters for your Session object - as described here: https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html

为了使用 SOCKS 代理,您必须为 Session 对象设置mail.smtp.socks.hostmail.smtp.socks.port参数 - 如下所述:https: //javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-摘要.html

回答by kark

Just try the following code, Easy to work...

只需尝试以下代码,轻松工作...

public class SendMail{

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

Include java-mail.jar, Run it....

包括java-mail.jar,运行它....

Copied from here

这里复制

回答by M Aqib Naeem

Since JavaMail 1.6.2, You can set proxy authentication properties for Session object for sending emails.

从 JavaMail 1.6.2 开始,您可以为 Session 对象设置代理身份验证属性以发送电子邮件。

Refer to the following documentation link. https://javaee.github.io/javamail/docs/api/

请参阅以下文档链接。https://javaee.github.io/javamail/docs/api/

The following properties are introduced newly and works fine with Proxy Authentication (Basic).

以下属性是新引入的,可与代理身份验证(基本)配合使用。

mail.smtp.proxy.host

mail.smtp.proxy.port

mail.smtp.proxy.user

mail.smtp.proxy.password