Apache Commons-Email java implementation steps

Many java developers are familiar with the venerable javax.mail.* packages and make use of them in their applications.

While it works well, it can often be cumbersome to work with and difficult to implement new features. Apache Commons-Email, now at version 1.4 (May 2015), provides a simpler interface to send emails with HTML format and attachments.

NOTE: The below examples assume that you are using an SMTP server that verifies the sender. You may need to modify the examples for your specific configuration. Additionally, I’ve left out the try/catch blocks for “Exceptions” that you will have to add.

Using javax.mail.* to send an text formatted message:

final String body = "Example email body";
final String emailFrom = "From User ";
final String emailTo = "To User
";
/* NOTE: 'session' and 'conn' are outside of the scope of this example but generally contain host and authentication information */
javax.mail.Session session = getSession(conn);
final javax.mail.Message message = new javax.mail.internet.MimeMessage(session);
message.setFrom(new javax.mail.internet.InternetAddress(emailFrom));
message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(emailTo));
message.setSubject(subj);
message.setText(body);
javax.mail.Transport.send(message);

Using commons-email for HTML email.

final String body = "Example email body";
final String emailFromAddr = "[email protected]";
final String emailFromName = "User From";
final String emailToAddr = "[email protected]";
final String emailToName = "User To";
final String username = "myusername";
final String password = "mypassword";

final org.apache.commons.mail.HtmlEmail email = new org.apache.commons.mail.HtmlEmail();
email.setHostName("localhost");
email.setSmtpPort(25);
email.setAuthentication(username, password);
email.setAuthenticator(new org.apache.commons.mail.DefaultAuthenticator(username, password));
//email.setSSLOnConnect(true);
final String charset = "UTF-8";
email.setCharset(charset);
email.setFrom(emailFromAddr,emailFromName);
email.setSubject(subj);

email.addTo(emailToAddr, emailToName);
//email.setDebug(true);

// set the alternative message
email.setTextMsg("Your email client does not support HTML messages.");

// set the html message
final StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(body);
sb.append("");
email.setHtmlMsg(sb.toString());
email.send();

Using commons-email with an inline attachment:

final org.apache.commons.mail.HtmlEmail email = new org.apache.commons.mail.HtmlEmail();
/* (insert code from example above above) */
String cid = null;
try{
final URL url = new URL("http://www.example.com/logo.gif");
final String img = email.embed(url, "Logo");
cid = "\"\"";
}
catch(final MalformedURLException ex){
// eat it!
}
// set the html message
final StringBuilder sb = new StringBuilder();
sb.append("");
if(cid!=null){ sb.append(cid); }
sb.append(body);
sb.append("");
email.setHtmlMsg(sb.toString());
email.send();

Code changes to use the library should not take very long as Commons-Email builds on top of javax.mail.*. In most cases, For Maven projects, you can remove the javax.mail references and simply add the new commons-email one to your pom.xml:


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>

REFERENCES:

Domain-based Message Authentication, Reporting & Conformance (DMARC) Email

DMARC was published in 2012 to build upon the SPF and DKIM email conventions for authorizing senders. It allows specification of policies and provides for reporting of actions performed under those policies.

Assistant:
http://www.kitterman.com/dmarc/assistant.html

DNS Entry Resembles:

_dmarc.example.com TXT v=DMARC1; p=none; rua=mailto:[email protected]; ruf=mailto:[email protected]; fo=0; adkim=r; aspf=r; pct=100; rf=afrf; ri=86400; sp=none

Simple verification…. send an email to this address and you will receive a response with your SPF, DKIM and DMARC compliance status:
mailto:[email protected]

REFERENCES:

DomainKeys Identified Mail (DKIM) Email

DomainKeys (originally from Yahoo!) and Cisco, and later as an industry collaboration, is a means for and organization to claim responsibility for sending a message, in a way that can be validated by a recipient. As a result, emails are “signed” by the outgoing SMTP server and can be verified against a DNS record. Depending upon the receiver, unsigned emails MAY be treated or marked as SPAM as they could be forgeries.

The below instructions assume Ubuntu (Debian) and Postfix, but could likely be modified for other platforms.

  • Install OpenDKIM:
    sudo apt-get install opendkim opendkim-tools
  • Setup initial configuration:

    sudo vi /etc/opendkim.conf

    ADD:
    Domain example.com
    KeyFile /etc/postfix/dkim.key
    Selector dkim
    SOCKET inet:[email protected]
    PidFile /var/run/opendkim/opendkim.pid
    #Canonicalization relaxed/relaxed
    ExternalIgnoreList file:/etc/opendkim/TrustedHostList
    InternalHosts file:/etc/opendkim/TrustedHostList
    LogWhy yes
  • Add trusted hosts… (and folder path, if needed)

    sudo mkdir /etc/opendkim


    sudo vi /etc/opendkim/TrustedHostList

    ADD:

    # External Hosts that OpenDKIM will Trust (add any appropriate values)
    localhost
    127.0.0.1
    10.1.10.1
  • sudo vi /etc/default/opendkim
    ADD:

    SOCKET="inet:[email protected]"
  • sudo vi /etc/postfix/main.cf
    ADD:

    # DKIM
    # --------------------------------------
    milter_default_action = accept
    milter_protocol = 2
    smtpd_milters = inet:127.0.0.1:8891
    non_smtpd_milters = inet:127.0.0.1:8891
  • Take a look around the following file, you may need it later:
    sudo vi /etc/postfix/master.cf
  • Generate your keys:

    opendkim-genkey -t -s dkim -d example.com

    NOTE: this creates dkim.private & dkim.txt, you “might” want to make backups of them 🙂

  • Change permissions on the file:

    sudo chown opendkim:opendkim dkim.private
  • Copy to the postfix folder:

    sudo cp dkim.private /etc/postfix/dkim.key
  • NOTE: I initially had a problem with dkim refusing connections, this MIGHT be needed.

    sudo adduser postfix opendkim
  • Start things back up together:

    sudo service opendkim start
    sudo service postfix restart
  • sudo vi dkim.txt
    (copy contents, remove t=y; as it indicates test mode)
    dkim._domainkey IN TXT ( "v=DKIM1; k=rsa; p=xxxxxxxxx" ) ;

  • Add DNS for DomainKey:

    _domainkey.example.com TXT o=~
  • Add DNS for DKIM:

    dkim._domainkey.example.com TXT v=DKIM1; k=rsa; p=xxxxxxxxx
  • NOTE: you will likely need to wait a few hours for your DNS entries to propagate.

  • Simple verification…. send an email to this address and you will receive a response with your SPF, DKIM and DMARC compliance status:
    mailto:[email protected]

REFERENCES:

Sender Policy Framework (SPF) Email

This is a simple mechanism, using DNS to certify that email from your domain comes from authorized servers. This is accomplished by adding a DNS record to identify the servers from which you send legitimate email. Emails sent from other servers MAY then be assumed as forged (SPAM) and blocked by the receiving email server.

NOTE: This can be easily spoofed, as such it should be a portion of your email security strategy, look into DKIM and DMARC too!

One thing that I initially did not understand… if you are supporting IPv6 and IPv4, you should merge your records onto a single DNS TXT entry:


example.com TXT v=spf1 a mx ip4:xxx.xxx.xxx.xxx ip6:xxxx:x:xxx:xxxx:xxx:xxxx:xxxx:xxx -all

REFERENCES:

Free Antivirus Software

So, a family member has recently approached me about virus scan products for Windows. It seems that, while he runs a commercial product, it’s a little dated and he does not keep up on the frequent updates, unfortunately this has put him into a position where his computer was infected and has become almost unusable. Using the same commercial products he’s unable to clean up the mess and has already lost many files.

I’ve been a convert to Avast for several years and even run it on my servers to scan for malicious content, it’s both free for non-commercial use and updates automatically.

Other products worth considering:

For Windows:

Unix/Linux:

Mac OS/X:

Cheers!

Pretty Good Privacy (PGP)

I’ve used PGP (Pretty Good Privacy) since I was in college. It provides for both digital signatures and strong encryption and content without the user having to go make extraordinary effort. The process uses what is known as Public Key Encryption and uses a Web Of Trust to certify individual users.

For years I used the original PGP 2.6.2, 5.x and 6.x products that were available as freeware. After PGP was acquired by a much larger commercial entity, most development has shifted to the open-source community that makes it available as GnuPG aka GPG.

There are several plugins available for common Email Clients such as Thunderbird and Outlook to natively integrate the functions into those applications. Additionally plugins are available for Firefox to enable encryption and signing of WebMail services such as GMail (Google Mail).

My public keys are available online at http://www.giantgeek.com/pgpkeys.asc, http://www.skotfred.com/pgpkeys.asc, or through most of the keyservers.

References:

I look forward to your signed/encrypted emails,
Cheers.