Commit d0a0cacef13ed667711cb0a277cbabf6ed4411a6
1 parent
25ac37e8
Exists in
master
and in
1 other branch
Métodos para envio de email para o govbr através da página de contatos.
Showing
5 changed files
with
160 additions
and
30 deletions
Show diff stats
src/main/java/br/com/ases/controller/ContatoController.java
... | ... | @@ -2,15 +2,13 @@ package br.com.ases.controller; |
2 | 2 | |
3 | 3 | import java.io.UnsupportedEncodingException; |
4 | 4 | import java.net.MalformedURLException; |
5 | -import java.nio.charset.Charset; | |
6 | -import java.util.regex.Matcher; | |
7 | -import java.util.regex.Pattern; | |
8 | 5 | |
9 | 6 | import javax.servlet.ServletContext; |
10 | 7 | |
11 | 8 | import org.apache.commons.mail.EmailException; |
12 | 9 | |
13 | 10 | import br.com.ases.model.entity.Contato; |
11 | +import br.com.ases.model.entity.EnvioEmailSemAutenticacao; | |
14 | 12 | import br.com.ases.model.utilities.Email; |
15 | 13 | import br.com.ases.model.utilities.StringHelper; |
16 | 14 | import br.com.ases.model.utilities.Validate; |
... | ... | @@ -20,7 +18,6 @@ import br.com.caelum.vraptor.Resource; |
20 | 18 | import br.com.caelum.vraptor.Result; |
21 | 19 | import br.com.caelum.vraptor.Validator; |
22 | 20 | import br.com.caelum.vraptor.ioc.spring.VRaptorRequestHolder; |
23 | -import br.com.caelum.vraptor.validator.ValidationMessage; | |
24 | 21 | |
25 | 22 | @Resource |
26 | 23 | @Path("/contato") |
... | ... | @@ -55,15 +52,17 @@ public class ContatoController { |
55 | 52 | Validate validate = new Validate(this.validator); |
56 | 53 | |
57 | 54 | if (validate.contato(contato)) { |
55 | + String respSendEmail; | |
56 | + | |
57 | + Email email = new Email(this.application.getRealPath("") + "/WEB-INF/mail.properties"); | |
58 | + | |
59 | + EnvioEmailSemAutenticacao envioEmailSemAutenticacao = new EnvioEmailSemAutenticacao(email.getHost(), Integer.toString(email.getPort())); | |
60 | + | |
61 | + respSendEmail = envioEmailSemAutenticacao.sendMail(contato.getEmail(),email.getTo(), StringHelper.convertFromUTF8(contato.getAssunto()), StringHelper.convertFromUTF8(contato.getMensagem()),email.getAuth(), email.getAuthUser(), email.getAuthPass()); | |
58 | 62 | |
59 | - Email email = new Email(this.application.getRealPath("") | |
60 | - + "/WEB-INF/mail.properties"); | |
61 | - String respSendEmail = email.sendEmail( | |
62 | - "Contato", | |
63 | - "govbr@planejamento.gov.br", contato.getNome(), | |
64 | - contato.getEmail(), | |
65 | - StringHelper.convertFromUTF8(contato.getAssunto()), | |
66 | - StringHelper.convertFromUTF8(contato.getMensagem()), true); | |
63 | + | |
64 | + /*String respSendEmail = email.sendEmail("Contato","govbr@planejamento.gov.br", contato.getNome(),contato.getEmail(),StringHelper.convertFromUTF8(contato.getAssunto()), | |
65 | + StringHelper.convertFromUTF8(contato.getMensagem()), true);*/ | |
67 | 66 | |
68 | 67 | if (respSendEmail.equals("")) { |
69 | 68 | result.include("mensagem", "Mensagem enviada com Sucesso"); | ... | ... |
src/main/java/br/com/ases/model/entity/EnvioEmailSemAutenticacao.java
0 → 100644
... | ... | @@ -0,0 +1,109 @@ |
1 | +package br.com.ases.model.entity; | |
2 | + | |
3 | +import java.util.Properties; | |
4 | + | |
5 | +import javax.mail.Message; | |
6 | +import javax.mail.Session; | |
7 | +import javax.mail.Transport; | |
8 | +import javax.mail.internet.InternetAddress; | |
9 | +import javax.mail.internet.MimeMessage; | |
10 | +import javax.mail.Authenticator; | |
11 | +import javax.mail.PasswordAuthentication; | |
12 | + | |
13 | +import org.apache.regexp.REUtil; | |
14 | + | |
15 | +public class EnvioEmailSemAutenticacao { | |
16 | + private String mailSMTPServer; | |
17 | + private String mailSMTPServerPort; | |
18 | + | |
19 | + /* | |
20 | + * caso queira mudar o servidor e a porta, so enviar para o contrutor | |
21 | + * os valor como string | |
22 | + */ | |
23 | + | |
24 | + public EnvioEmailSemAutenticacao() | |
25 | + { | |
26 | + | |
27 | + } | |
28 | + public EnvioEmailSemAutenticacao(String mailSMTPServer, String mailSMTPServerPort) { //Para outro Servidor | |
29 | + this.mailSMTPServer = mailSMTPServer; | |
30 | + this.mailSMTPServerPort = mailSMTPServerPort; | |
31 | + } | |
32 | + public String sendMail(String from, String to, String subject, String message, String comAutenticacao, String authuser, String authpass) { | |
33 | + Properties props = new Properties(); | |
34 | + String retorno = ""; | |
35 | + | |
36 | + props.put("mail.transport.protocol", "smtp"); //define protocolo de envio como SMTP | |
37 | + props.put("mail.smtp.starttls.enable","true"); | |
38 | + props.put("mail.smtp.host", mailSMTPServer); //server SMTP do GMAIL | |
39 | + props.put("mail.smtp.auth", comAutenticacao); //ativa autenticacao | |
40 | + props.put("mail.smtp.user", from); //usuario ou seja, a conta que esta enviando o email (tem que ser do GMAIL) | |
41 | + props.put("mail.debug", "false"); | |
42 | + props.put("mail.smtp.port", mailSMTPServerPort); //porta | |
43 | + | |
44 | + //Cria um autenticador que sera usado a seguir | |
45 | + SimpleAuth auth = null; | |
46 | + auth = new SimpleAuth (authuser,authpass); | |
47 | + //Session - objeto que ira realizar a conexão com o servidor | |
48 | + /*Como há necessidade de autenticação é criada uma autenticacao que | |
49 | + * é responsavel por solicitar e retornar o usuário e senha para | |
50 | + * autenticação */ | |
51 | + Session session = Session.getDefaultInstance(props, auth); | |
52 | + session.setDebug(true); //Habilita o LOG das ações executadas durante o envio do email | |
53 | + //Objeto que contém a mensagem | |
54 | + Message msg = new MimeMessage(session); | |
55 | + try { | |
56 | + //Setando o destinatário | |
57 | + msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); | |
58 | + //Setando a origem do email | |
59 | + msg.setFrom(new InternetAddress(from)); | |
60 | + //Setando o assunto | |
61 | + msg.setSubject(subject); | |
62 | + //Setando o conteúdo/corpo do email | |
63 | + msg.setContent(message,"text/html"); | |
64 | + | |
65 | + | |
66 | + } catch (Exception e) { | |
67 | + retorno = e.getMessage(); | |
68 | + System.out.println(">> Erro: Completar Mensagem"); | |
69 | + e.printStackTrace(); | |
70 | + return retorno; | |
71 | + } | |
72 | + //Objeto encarregado de enviar os dados para o email | |
73 | + Transport tr; | |
74 | + try { | |
75 | + tr = session.getTransport("smtp"); //define smtp para transporte | |
76 | + /* | |
77 | + * 1 - define o servidor smtp | |
78 | + * 2 - seu nome de usuario do gmail | |
79 | + * 3 - sua senha do gmail | |
80 | + */ | |
81 | + tr.connect(mailSMTPServer, authuser, authpass); | |
82 | + msg.saveChanges(); // don't forget this | |
83 | + //envio da mensagem | |
84 | + tr.sendMessage(msg, msg.getAllRecipients()); | |
85 | + | |
86 | + tr.close(); | |
87 | + | |
88 | + } catch (Exception e) { | |
89 | + // TODO Auto-generated catch block | |
90 | + System.out.println(">> Erro: Envio Mensagem"); | |
91 | + retorno = e.getMessage(); | |
92 | + } | |
93 | + return retorno; | |
94 | + } | |
95 | + | |
96 | + | |
97 | +} | |
98 | +//clase que retorna uma autenticacao para ser enviada e verificada pelo servidor smtp | |
99 | +class SimpleAuth extends Authenticator { | |
100 | + public String username = null; | |
101 | + public String password = null; | |
102 | + public SimpleAuth(String user, String pwd) { | |
103 | + username = user; | |
104 | + password = pwd; | |
105 | + } | |
106 | + protected PasswordAuthentication getPasswordAuthentication() { | |
107 | + return new PasswordAuthentication (username,password); | |
108 | + } | |
109 | +} | |
0 | 110 | \ No newline at end of file | ... | ... |
src/main/java/br/com/ases/model/utilities/Email.java
... | ... | @@ -5,6 +5,10 @@ import java.net.MalformedURLException; |
5 | 5 | import java.util.Date; |
6 | 6 | import java.util.Properties; |
7 | 7 | |
8 | +import lombok.AccessLevel; | |
9 | +import lombok.Getter; | |
10 | +import net.htmlparser.jericho.Source; | |
11 | + | |
8 | 12 | import org.apache.commons.mail.EmailAttachment; |
9 | 13 | import org.apache.commons.mail.EmailException; |
10 | 14 | import org.apache.commons.mail.HtmlEmail; |
... | ... | @@ -16,13 +20,17 @@ import org.apache.commons.mail.MultiPartEmail; |
16 | 20 | * @version 1.0*/ |
17 | 21 | public class Email { |
18 | 22 | |
19 | - private String authUser; | |
20 | - private String authPass; | |
21 | - private String host; | |
22 | - private int port; | |
23 | + @Getter private String authUser; | |
24 | + @Getter private String authPass; | |
25 | + @Getter private String host; | |
26 | + @Getter private String auth; | |
27 | + @Getter private int port; | |
28 | + @Getter private String to; | |
29 | + | |
23 | 30 | private MultiPartEmail email; |
24 | 31 | private EmailAttachment anexo; |
25 | 32 | |
33 | + | |
26 | 34 | private void initConf(String path){ |
27 | 35 | ManagerProperties managerProperties = new ManagerProperties(); |
28 | 36 | try { |
... | ... | @@ -32,6 +40,8 @@ public class Email { |
32 | 40 | this.port = Integer.parseInt(prop.getProperty("prop.email.port")); |
33 | 41 | this.authUser = prop.getProperty("prop.email.authuser"); |
34 | 42 | this.authPass = prop.getProperty("prop.email.authpass"); |
43 | + this.auth = prop.getProperty("prop.email.auth"); | |
44 | + this.to = prop.getProperty("prop.email.to"); | |
35 | 45 | |
36 | 46 | } catch (IOException e) { |
37 | 47 | // TODO Auto-generated catch block |
... | ... | @@ -42,14 +52,17 @@ public class Email { |
42 | 52 | |
43 | 53 | /** |
44 | 54 | * @param String host, int port, String authUser, String authPass*/ |
45 | - public Email(String host, int port, String authUser, String authPass){ | |
55 | + public Email(String host, int port, String authUser, String authPass, String auth, String to){ | |
46 | 56 | this.host = host; |
47 | 57 | this.port = port; |
48 | 58 | this.authUser = authUser; |
49 | 59 | this.authPass = authPass; |
60 | + this.auth = auth; | |
61 | + this.to = to; | |
50 | 62 | this.email = new HtmlEmail(); |
63 | + | |
51 | 64 | } |
52 | - | |
65 | + | |
53 | 66 | /** |
54 | 67 | * @param String path. Caminho do arquivo mail.properties*/ |
55 | 68 | public Email(String path) { |
... | ... | @@ -75,7 +88,11 @@ public class Email { |
75 | 88 | this.email.setMsg("<p>Olá, <b>"+nomeRemetente+"</b> enviou a seguinte mensagem:</p> \n "+mensagem); //conteudo do e-mail |
76 | 89 | |
77 | 90 | this.email.setSentDate(new Date()); |
78 | - this.email.setAuthentication(this.authUser, this.authPass); | |
91 | + | |
92 | + //this.email.setAuthentication(this.authUser, this.authPass); | |
93 | + | |
94 | + | |
95 | + | |
79 | 96 | this.email.setSmtpPort(this.port); |
80 | 97 | this.email.setSSL(true); |
81 | 98 | this.email.setTLS(true); | ... | ... |
src/main/java/br/com/ases/model/utilities/Validate.java
... | ... | @@ -24,37 +24,38 @@ public class Validate { |
24 | 24 | boolean isValido = true; |
25 | 25 | |
26 | 26 | if(contato.getNome() == null){ |
27 | - this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! Favor preencher o campo NOME!", "error")); | |
27 | + this.validator.add(new ValidationMessage("Favor preencher o campo NOME!", "error")); | |
28 | 28 | isValido = false; |
29 | 29 | }else |
30 | 30 | if(contato.getNome().length() > 200){ |
31 | - this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! Ocorreu o problema: o campo NOME aceita até 200 caracteres.", "error")); | |
31 | + this.validator.add(new ValidationMessage("O campo NOME aceita até 200 caracteres.", "error")); | |
32 | 32 | isValido = false; |
33 | 33 | } |
34 | 34 | |
35 | 35 | if(contato.getEmail() == null){ |
36 | - this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! Favor preencher o campo E-MAIL!", "error")); | |
36 | + this.validator.add(new ValidationMessage("Favor preencher o campo E-MAIL!", "error")); | |
37 | 37 | isValido = false; |
38 | 38 | }else{ |
39 | 39 | Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$"); |
40 | 40 | Matcher m = p.matcher(contato.getEmail()); |
41 | 41 | if (!m.find()){ |
42 | - this.validator.add(new ValidationMessage(" Não foi possível enviar a mensagem! E-MAIL '"+contato.getEmail()+"' considerado inválido!", "error")); | |
42 | + //this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! E-MAIL '"+contato.getEmail()+"' considerado inválido!", "error")); | |
43 | + this.validator.add(new ValidationMessage("E-MAIL considerado inválido!", "error")); | |
43 | 44 | isValido = false; |
44 | 45 | } |
45 | 46 | } |
46 | 47 | |
47 | 48 | if(contato.getAssunto() == null){ |
48 | - this.validator.add(new ValidationMessage(" Não foi possível enviar a mensagem! Favor escolher uma das opções no campo ASSUNTO!", "error")); | |
49 | + this.validator.add(new ValidationMessage("Favor escolher uma das opções no campo ASSUNTO!", "error")); | |
49 | 50 | isValido = false; |
50 | 51 | } |
51 | 52 | |
52 | 53 | if(contato.getMensagem() == null){ |
53 | - this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! Favor preencher o campo MENSAGEM!", "error")); | |
54 | + this.validator.add(new ValidationMessage("Favor preencher o campo MENSAGEM!", "error")); | |
54 | 55 | isValido = false; |
55 | 56 | }else |
56 | 57 | if(contato.getMensagem().length() > 500){ |
57 | - this.validator.add(new ValidationMessage("Não foi possível enviar a mensagem! Ocorreu o problema: o campo MENSAGEM aceita até 500 caracteres.", "error")); | |
58 | + this.validator.add(new ValidationMessage("O campo MENSAGEM aceita até 500 caracteres.", "error")); | |
58 | 59 | isValido = false; |
59 | 60 | } |
60 | 61 | ... | ... |
src/main/webapp/WEB-INF/mail.properties
1 | -prop.email.host = 161.148.21.220 | |
2 | -prop.email.port = 465 | |
3 | -prop.email.authuser = 96409975520 | |
4 | -prop.email.authpass = Erdos_200244 | |
5 | 1 | \ No newline at end of file |
2 | +#com autenticação alterar o valor da chave "prop.email.auth = false" para "prop.email.auth = true" e | |
3 | +#atribuir login e senha nas chaves respectivas "prop.email.authuser = ", "prop.email.authpass =". | |
4 | +prop.email.host = 189.9.150.53 | |
5 | +prop.email.port = 25 | |
6 | +prop.email.authuser = "" | |
7 | +prop.email.authpass = "" | |
8 | +prop.email.auth = false | |
9 | +prop.email.to = govbr@planejamento.gov.br | |
6 | 10 | \ No newline at end of file | ... | ... |