arg20
arg20

Reputation: 4991

Sending e-mails in JAVA EE 6

I'm developing a Java EE 6 application deployed on glassfish, I keep reading tutorials about how to send emails but they seem either outdated or too complicated. I was hoping that may be in this specification there's a rather simple way to send mail since so many things have become so much simpler. Can you point me in the right direction or may be show me some sample code?

Upvotes: 7

Views: 9990

Answers (2)

Bruno_Condemi
Bruno_Condemi

Reputation: 181

The JEE App Server should provide the email resource. The only think you need to do is lookup the resource (I suppose it is configured) and send the email.

//Mail  Resource injection not working on wildfly 10
//@Resource(lookup = "java:/futuramail")
private Session mailSession;

@Asynchronous
@Lock(LockType.READ)
    public void sendMail(String recipient, String subject, String text) {
        try {

            InitialContext ic = new InitialContext();
            mailSession = (Session) ic.lookup("java:/futuramail");
            MimeMessage message = new MimeMessage(mailSession);
            Address[] to = new InternetAddress[]{new InternetAddress(recipient)};
            message.setRecipients(Message.RecipientType.TO, to);
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setContent(text, "text/html");
            //message.setText(text);
            Transport.send(message);
            System.out.println("mail sent");
        } catch (MessagingException me) {
            me.printStackTrace();
        } catch (NamingException ex) {
            Logger.getLogger(MailProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Upvotes: 0

CoolBeans
CoolBeans

Reputation: 20810

You can utilize apache commons email or if you are using Spring then use spring mail. There is always JavaMail if you don't want to use any of the wrapper libraries and a code sample on it.

All of these links have code examples.

Upvotes: 13

Related Questions