Sending email on Apache TomEE

Recently I am playing with Apache TomEE, since I want to create an application with only a subset of Java EE functionality. So, TomEE as Java EE Web-profile fits well 😉

This time around I am blogging about my findings on sending email with TomEE. Actually having done all the troubleshooting, it is quite simple, and hence it is going to be quite a short article.

Setup

Setting up TomEE is very simple, so I will not go into that. Just a note here I am using GMail account, so go and create your GMail account.

Here is another important part. Make sure you you turn ON 'Allow less secure apps' on Google settings here.

Configuring ‘tomee.xml’

Next, configure the file on <installation location>/conf/tomee.xml

<?xml version="1.0" encoding="UTF-8"?>
<tomee>
    <!-- see http://tomee.apache.org/containers-and-resources.html -->

    <!-- activate next line to be able to deploy applications in apps -->
    <!-- <Deployments dir="apps" /> -->
    <Resource id="tomee/mail/GMailSMTP" type="javax.mail.Session">
	mail.smtp.host=smtp.gmail.com
	mail.smtp.starttls.enable=true
	mail.smtp.port=587
	mail.transport.protocol=smtp
	mail.smtp.auth=true
	mail.smtp.user=<!-- your email address -->
	password=<!-- your password, and not 'mail.smtp.password' -->	
    </Resource>
</tomee>

Use it by injection of ‘@Resource’

Now you can use it via injection

// imports omitted

@Stateless
@LocalBean
@Path(value = "workline")
public class MailService {
    @Resource(mappedName = "java:comp/env/tomee/mail/GMailSMTP")
    private Session smtpSession;

    public boolean sendMail() throws NamingException {
        final Message message = new MimeMessage(this.smtpSession);
        try {
            message.setRecipients(Message.RecipientType.TO, new Address[]{
                new InternetAddress("someone@gmail.com")
            });
            message.setSubject("Email from TomEE");
            message.setSentDate(new Date());
            message.setText("Email from TomEE");
            Transport.send(message);
        } catch (Exception e) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
            return false;
        }
        return true;
    }
}

Troubleshooting:

I had an issue whereby the @Resource injection was null, with the log warning states: WARNING: Injection: No such property .... After hours of google-ing around, apparently this was caused by conflict of the mail library which may be included in my apps, against what is provided by the underlying TomEE server. Marking the scope as provided in my pom.xml fix this (darkzone, 2014).

References

darkZone, 2014, ‘java.lang.ClassCastException: javax.mail.Session cannot be cast to javax.mail.Session’, Stackoverflow.com, accessed on 17 February 2016

virtualskynet, 2013, Code sample: tomee.xml, GitHub, accessed on 17 February 2016

Advertisements