简体   繁体   中英

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?

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.

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM