Send mail from a JSF page using beans

I am building a web application using jsf and primefaces and my question is how to send an email via the contact form of the site (I have done this using php before, very easy, but never used jsf). I created a form on the contact.xhtml page as well as a bean class to support this, and all the form needs to do is send the bean data to a predefined mail (i.e. gmail). I also found some “tutorials” on how to send email using JavaMail, but nothing works properly. The form itself consists of the name, email, and message fields.

Can someone write how to do this, or give me a link. I would be very grateful.

I need my site to work (online), or I can check it with localhost.

Thanks in advance.

+6
source share
3 answers

In a very short time:

  • do <h:commandButton action="#{yourBean.send}"
  • make a managed bean annotated using @ManagedBean("yourBean") , which has a send(..) method
  • get commons-email and read its short "User Guide"; get a working smtp server (commons-email depends on JavaMail, so get this also in the classpath)
  • in the send method, use commons-email to send email.

(You must go through the JSF tutorial to learn how to collect form parameters)

Please note that java is a bit more complicated. "Send mail via JSF" is not a good question. It consists of two questions:

  • how to get the form submitted in jsf (each tutorial explains it)
  • how to send email in java in general
+6
source

It's all about how to capture JSF output. My approach is to simply invoke the JSF page via JAX-RS, draw output and put it in email. Be careful to make the page as simple as possible (JSF likes to add a lot of JS code) and set absolute URLs for resources. Here is my code (simplified):

 @Resource(name = "mail/mySession") Session mailSession; //make request, capture output Client client = ClientBuilder.newClient(); String htmlBody = client.target("http://localhost:8080/AppName/jsfpage.xhtml") .queryParam("id", 10) //we can add some params .request() .get(String.class); //send email Message message = new MimeMessage(mailSession); message.setFrom(); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(" asd@asd.pl ")); message.setHeader("X-Mailer", "JavaMail"); message.setSubject("Subject here"); message.setContent(htmlBody, "text/html; charset=utf-8"); //set captured html as content message.setSentDate(new Date()); Transport.send(message); 
+2
source

In my practice, SEAM Mail really helps send mail.

Here you can find a good tutorial:

Sending mail from Seam JSF-mail

+1
source

Source: https://habr.com/ru/post/899412/


All Articles