How to send email programatically from Java to easyname’s SMTP server

If you want to send email then it's best to do it over the email server that is the authoritative one for the sender email address.

If you are using easyname and want to send email from a Java program from an easyname-controlled email address via easyname's email servers, this is how you do it.

Update: Thanks to AndiT. RobinK, DavidZ for pointing out that a better way to do this would be to install a local mail server (MTA) e.g. postfix, send the email from Java to the MTA, and have the MTA send the email to easyname. If easyname experiences a problem, the email will be queued by the MTA. Configuring an MTA is outside the scope of this article :)

The "from" address must exist at easyname. The username and password in the following code is an "email box" name and password from the same easyname account.

Thanks to this article! http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

String sender = "foo@myeasynamedomain.com";
String emailBoxName = "12345mail2";
String emailBoxPassword = "foo";

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.easyname.eu");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(emailBoxName, emailBoxPassword);
    }
  });
  
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.addRecipient(RecipientType.TO, ...);
msg.setSubject(...);
msg.setContent(...);

Transport.send(msg);

This article is © Adrian Smith.
It was originally published on 21 Aug 2014
More on: Java | easyname.com