DoTheGenes DoTheGenes - 3 months ago 35
Java Question

JavaMail - Setting up ports, proxy and firewall

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

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 = "";

// Senders ID needs to be set
String from = "";

// Assuming localhost
String host = "localhost";

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

// Setup mail server
properties.setProperty("", 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");

System.out.println("Message sent...");
}catch (MessagingException mex) {


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(
        new ServerConfig("localhost", thePort, theUser, thePasswordd),
        new ProxyConfig(proxyHost, proxyPort /*, proxyUser, proxyPassword */)

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

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

A lot less code and very expressive.