سؤال

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?

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 = "test@test.com";

    // Senders ID needs to be set
    String from = "mytest@test.com";

    // 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();
    }
}
هل كانت مفيدة؟

المحلول 2

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.

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

Here's how your code would look with 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", "mytest@test.com")
        .to("test", "test@test.com")
        .subject("This is the subject line")
        .textHTML("<h1>This is the actual message</h1>")
        .build());

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

A lot less code and very expressive.

نصائح أخرى

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

Refer to the following documentation link. 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

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

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

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.

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

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

public class SendMail{

    public static void main(String[] args) {

        final String username = "from@gmail.com";
        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("from@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("to@gmail.com"));
            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....

Copied from here

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top