fixes bug#0014278
dev: thiago qua: wallysson Implementação efetuada. git-svn-id: http://desenvolvimento.rjconsultores.com.br/repositorio/sco/AdmVenta/Model/trunk/modelWeb@94496 d1611594-4594-4d17-8e1d-87c2c4800839master
parent
4c46b94bea
commit
fc9d5bebb0
|
@ -41,6 +41,8 @@ public class EmpresaEmail implements Serializable {
|
|||
private String emailDe;
|
||||
@Column(name = "EMAILCOPIAOCULTA")
|
||||
private String emailCopiaOculta;
|
||||
@Column(name = "DESTINATARIO")
|
||||
private String destinatario;
|
||||
@OneToOne
|
||||
@JoinColumn(name = "EMPRESA_ID")
|
||||
private Empresa empresa;
|
||||
|
@ -116,6 +118,14 @@ public class EmpresaEmail implements Serializable {
|
|||
this.emailCopiaOculta = emailCopiaOculta;
|
||||
}
|
||||
|
||||
public String getDestinatario() {
|
||||
return destinatario;
|
||||
}
|
||||
|
||||
public void setDestinatario(String destinatario) {
|
||||
this.destinatario = destinatario;
|
||||
}
|
||||
|
||||
public void setEmailDe(String emailDe) {
|
||||
this.emailDe = emailDe;
|
||||
}
|
||||
|
|
|
@ -31,7 +31,7 @@ public class LogHistoricoContingencia implements Serializable {
|
|||
@Basic(optional = false)
|
||||
@GeneratedValue(strategy = GenerationType.AUTO, generator = "LOG_HISTORICO_CONTINGENCIA_SEQ")
|
||||
@Column(name = "LOGHISTORICOCONTINGENCIA_ID")
|
||||
private Long LogHistoricoContingenciaId;
|
||||
private Long logHistoricoContingenciaId;
|
||||
|
||||
@Column(name = "MOTIVO")
|
||||
private String motivo;
|
||||
|
@ -54,13 +54,16 @@ public class LogHistoricoContingencia implements Serializable {
|
|||
|
||||
@Column(name = "STATUS")
|
||||
private String status;
|
||||
|
||||
@Column(name = "IND_AMBIENTE")
|
||||
private Integer ambiente;
|
||||
|
||||
public Long getLogHistoricoContingenciaId() {
|
||||
return LogHistoricoContingenciaId;
|
||||
return logHistoricoContingenciaId;
|
||||
}
|
||||
|
||||
public void setLogHistoricoContingenciaId(Long logHistoricoContingenciaId) {
|
||||
LogHistoricoContingenciaId = logHistoricoContingenciaId;
|
||||
this.logHistoricoContingenciaId = logHistoricoContingenciaId;
|
||||
}
|
||||
|
||||
public String getMotivo() {
|
||||
|
@ -110,4 +113,12 @@ public class LogHistoricoContingencia implements Serializable {
|
|||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Integer getAmbiente() {
|
||||
return ambiente;
|
||||
}
|
||||
|
||||
public void setAmbiente(Integer ambiente) {
|
||||
this.ambiente = ambiente;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,32 @@
|
|||
package com.rjconsultores.ventaboletos.enums;
|
||||
|
||||
public enum EAmbienteContingencia {
|
||||
|
||||
PRODUCAO(1, "Produção"),
|
||||
HOMOLOGACAO(2, "Homologação");
|
||||
|
||||
private Integer id;
|
||||
private String descricao;
|
||||
|
||||
private EAmbienteContingencia(Integer id, String descricao) {
|
||||
this.id = id;
|
||||
this.descricao = descricao;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getDescricao() {
|
||||
return descricao;
|
||||
}
|
||||
|
||||
public static EAmbienteContingencia getAmbienteContingencia(Integer id) {
|
||||
for (EAmbienteContingencia ambiente : EAmbienteContingencia.values()) {
|
||||
if (ambiente.getId().equals(id)) {
|
||||
return ambiente;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Ambiente contigência não definido");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.rjconsultores.ventaboletos.enums;
|
||||
|
||||
public enum EStatusContingencia {
|
||||
|
||||
NORMAL(1, "Normal"),
|
||||
CONTINGENCIA(2, "Contingência");
|
||||
|
||||
private Integer id;
|
||||
private String descricao;
|
||||
|
||||
private EStatusContingencia(Integer id, String descricao) {
|
||||
this.id = id;
|
||||
this.descricao = descricao;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getDescricao() {
|
||||
return descricao;
|
||||
}
|
||||
|
||||
public static EStatusContingencia getStatusContingencia(Integer id) {
|
||||
for (EStatusContingencia status : EStatusContingencia.values()) {
|
||||
if (status.getId().equals(id)) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Status contigência não definido");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.rjconsultores.ventaboletos.enums;
|
||||
|
||||
public enum TypeContentEmail {
|
||||
|
||||
TEXT_HTML("text/html");
|
||||
public String valor;
|
||||
|
||||
TypeContentEmail(String valorConst){
|
||||
valor = valorConst;
|
||||
}
|
||||
}
|
|
@ -5,6 +5,7 @@ public enum TypeEventListener {
|
|||
ON_CHANGE("onChange"),
|
||||
ON_CLICK("onClick"),
|
||||
ON_DOUBLE_CLICK("onDoubleClick"),
|
||||
ON_CHECK("onCheck"),
|
||||
ON_CTRL_KEY("onCtrlKey");
|
||||
|
||||
private String event;
|
||||
|
|
|
@ -16,11 +16,7 @@ public class BusinessException extends Exception {
|
|||
* - La clave del archivo de traducción
|
||||
*/
|
||||
public BusinessException(String message) {
|
||||
super(Labels.getLabel(message));
|
||||
}
|
||||
|
||||
public BusinessException(String message, Boolean label) {
|
||||
super(message);
|
||||
super(Labels.getLabel(message) == null ? message :Labels.getLabel(message));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -0,0 +1,139 @@
|
|||
package com.rjconsultores.ventaboletos.rest;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.jms.IllegalStateException;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.codehaus.jettison.json.JSONException;
|
||||
import org.codehaus.jettison.json.JSONObject;
|
||||
import org.zkoss.zkplus.spring.SpringUtil;
|
||||
|
||||
import com.rjconsultores.ventaboletos.service.ConstanteService;
|
||||
/**
|
||||
* @author vjcor
|
||||
*
|
||||
*/
|
||||
public class ContingenciaClienteRest {
|
||||
|
||||
|
||||
public enum ETipoEnvio {
|
||||
GET, POST;
|
||||
}
|
||||
|
||||
private static final String CONSTANTE_BPE_URL = "BPE_URL";
|
||||
private static final String CREDENCIAIS = "rjconsultores:RJ#C0nsul10res@2019";
|
||||
private static final String PATH_CONSULTA_STATUS = "/BPeRS/rest/adm/contingencia/tipoEmissaoEmpresa";
|
||||
private static final String PATH_DEFINIR_STATUS = "/BPeRS/rest/adm/contingencia/definirTipoEmissaoEmpresa";
|
||||
|
||||
private static Logger log = Logger.getLogger(ContingenciaClienteRest.class);
|
||||
|
||||
private static ContingenciaClienteRest instance;
|
||||
|
||||
private ContingenciaClienteRest() {
|
||||
}
|
||||
|
||||
public static synchronized ContingenciaClienteRest getInstance() {
|
||||
if(instance == null) {
|
||||
instance = new ContingenciaClienteRest();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public Integer consultar(String uf, String ambiente, String cnpj) {
|
||||
try {
|
||||
return verificarStatus(getURI(PATH_CONSULTA_STATUS, uf, ambiente, cnpj), ETipoEnvio.GET);
|
||||
} catch (IOException e) {
|
||||
log.error(e);
|
||||
} catch (JSONException e) {
|
||||
log.error(e);
|
||||
} catch (IllegalStateException e) {
|
||||
log.error(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Integer definir(String uf, String ambiente, String cnpj, Integer idStatus) {
|
||||
try {
|
||||
return verificarStatus(getURI(PATH_DEFINIR_STATUS, uf, ambiente, cnpj, idStatus), ETipoEnvio.POST);
|
||||
} catch (IOException e) {
|
||||
log.error(e);
|
||||
} catch (JSONException e) {
|
||||
log.error(e);
|
||||
} catch (IllegalStateException e) {
|
||||
log.error(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String buscarConstanteURL() {
|
||||
return getConstanteService().buscarPorNomeConstante(CONSTANTE_BPE_URL).getValorconstante();
|
||||
}
|
||||
|
||||
private ConstanteService getConstanteService() {
|
||||
return (ConstanteService) SpringUtil.getBean("constanteService");
|
||||
}
|
||||
|
||||
private Integer verificarStatus(String uri, ETipoEnvio tipoEnvio) throws IOException, JSONException, IllegalStateException {
|
||||
HttpClient client = new DefaultHttpClient();
|
||||
HttpUriRequest request = getRequest(uri, tipoEnvio);
|
||||
HttpResponse response = client.execute(request);
|
||||
|
||||
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
|
||||
&& response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
|
||||
throw new IllegalStateException("Ocorreu um erro na requisição.");
|
||||
}
|
||||
|
||||
return getRetornoJSON(response);
|
||||
}
|
||||
|
||||
private Integer getRetornoJSON(HttpResponse response) throws IOException, JSONException {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
if (entity != null) {
|
||||
String rest = EntityUtils.toString(entity);
|
||||
JSONObject result = new JSONObject(rest);
|
||||
return Integer.valueOf(result.get("tpEmis").toString());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private HttpUriRequest getRequest(String uri, ETipoEnvio tipoEnvio) {
|
||||
HttpUriRequest request = ETipoEnvio.GET.equals(tipoEnvio) ? new HttpGet(uri) : new HttpPost(uri);
|
||||
request.addHeader("Authorization", getAuthorization());
|
||||
return request;
|
||||
}
|
||||
|
||||
private String getAuthorization() {
|
||||
return "Basic " + new String(Base64.encodeBase64(CREDENCIAIS.getBytes()));
|
||||
}
|
||||
|
||||
private String getURI(String path, String uf, String ambiente, String cnpj) {
|
||||
StringBuilder uri = new StringBuilder();
|
||||
uri.append(buscarConstanteURL());
|
||||
uri.append(path);
|
||||
uri.append("?uf=").append(uf);
|
||||
uri.append("&ambiente=").append(ambiente);
|
||||
uri.append("&cnpj=").append(cnpj);
|
||||
|
||||
return uri.toString();
|
||||
}
|
||||
|
||||
private String getURI(String path, String uf, String ambiente, String cnpj, Integer idStatus) {
|
||||
StringBuilder uri = new StringBuilder();
|
||||
uri.append(getURI(path, uf, ambiente, cnpj));
|
||||
uri.append("&tpEmis=").append(idStatus);
|
||||
|
||||
return uri.toString();
|
||||
}
|
||||
}
|
|
@ -2,6 +2,8 @@ package com.rjconsultores.ventaboletos.service;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import javax.mail.SendFailedException;
|
||||
|
||||
import com.rjconsultores.ventaboletos.entidad.LogHistoricoContingencia;
|
||||
import com.rjconsultores.ventaboletos.exception.BusinessException;
|
||||
|
||||
|
@ -9,5 +11,5 @@ public interface ContingenciaService {
|
|||
|
||||
public List<LogHistoricoContingencia> buscarHistorico(Integer empresaID, Integer estadoID);
|
||||
|
||||
public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws BusinessException;
|
||||
public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws SendFailedException, BusinessException;
|
||||
}
|
||||
|
|
|
@ -3,14 +3,24 @@ package com.rjconsultores.ventaboletos.service.impl;
|
|||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
|
||||
import javax.mail.SendFailedException;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.rjconsultores.ventaboletos.dao.LogHistoricoContingenciaDAO;
|
||||
import com.rjconsultores.ventaboletos.entidad.EmpresaEmail;
|
||||
import com.rjconsultores.ventaboletos.entidad.EmpresaEmailConfig;
|
||||
import com.rjconsultores.ventaboletos.entidad.LogHistoricoContingencia;
|
||||
import com.rjconsultores.ventaboletos.enums.EAmbienteContingencia;
|
||||
import com.rjconsultores.ventaboletos.enums.EStatusContingencia;
|
||||
import com.rjconsultores.ventaboletos.exception.BusinessException;
|
||||
import com.rjconsultores.ventaboletos.rest.ContingenciaClienteRest;
|
||||
import com.rjconsultores.ventaboletos.service.ContingenciaService;
|
||||
import com.rjconsultores.ventaboletos.service.EmpresaEmailConfigService;
|
||||
import com.rjconsultores.ventaboletos.service.EmpresaEmailService;
|
||||
import com.rjconsultores.ventaboletos.utilerias.SendMail;
|
||||
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
|
||||
|
||||
/**
|
||||
|
@ -20,16 +30,23 @@ import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
|
|||
@Service("contingenciaService")
|
||||
public class ContingenciaServiceImpl implements ContingenciaService {
|
||||
|
||||
private static final String EMAIL_COPIA_OCULTA = "suportesco@rjconsultores.com.br";
|
||||
|
||||
@Autowired
|
||||
private LogHistoricoContingenciaDAO histContingenciaDAO;
|
||||
|
||||
@Autowired
|
||||
private EmpresaEmailService empresaEmailService;
|
||||
|
||||
@Autowired
|
||||
private EmpresaEmailConfigService empresaEmailConfigService;
|
||||
|
||||
public List<LogHistoricoContingencia> buscarHistorico(Integer empresaID, Integer estadoID) {
|
||||
return histContingenciaDAO.buscarHistorico(empresaID, estadoID);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws BusinessException {
|
||||
|
||||
public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws SendFailedException, BusinessException {
|
||||
historicoCont.setUsuario(UsuarioLogado.getUsuarioLogado());
|
||||
historicoCont.setDataHora(Calendar.getInstance().getTime());
|
||||
|
||||
|
@ -45,7 +62,48 @@ public class ContingenciaServiceImpl implements ContingenciaService {
|
|||
throw new BusinessException("Não é possível salvar sem o motivo referente");
|
||||
}
|
||||
|
||||
ContingenciaClienteRest.getInstance().definir(historicoCont.getEstado().getCveestado(),
|
||||
historicoCont.getAmbiente().toString(), historicoCont.getEmpresa().getCnpj(),
|
||||
Integer.valueOf(historicoCont.getStatus()));
|
||||
|
||||
if (EStatusContingencia.CONTINGENCIA.equals(getStatusContingencia(historicoCont))) {
|
||||
enviaEmail(historicoCont);
|
||||
}
|
||||
|
||||
return histContingenciaDAO.suscribir(historicoCont);
|
||||
}
|
||||
|
||||
private EStatusContingencia getStatusContingencia(LogHistoricoContingencia historicoCont) {
|
||||
return EStatusContingencia.getStatusContingencia(Integer.valueOf(historicoCont.getStatus()));
|
||||
}
|
||||
|
||||
private void enviaEmail(LogHistoricoContingencia historicoCont) throws SendFailedException {
|
||||
SendMail mail = new SendMail();
|
||||
EmpresaEmail empresaEmail = empresaEmailService.buscarPorEmpresa(historicoCont.getEmpresa());
|
||||
EmpresaEmailConfig empresaEmailConfig = empresaEmailConfigService.buscarPorEmpresa(historicoCont.getEmpresa());
|
||||
mail.setAuth(empresaEmailConfig.getIndAutenticacao());
|
||||
mail.setEmailFrom(empresaEmail.getEmailDe());
|
||||
mail.setSmtpHost(empresaEmailConfig.getSmtp());
|
||||
mail.setSmtpPassword(empresaEmailConfig.getSenha());
|
||||
mail.setSmtpPort(empresaEmailConfig.getSmtpPorta());
|
||||
mail.setSmtpUser(empresaEmailConfig.getSmtpEmail());
|
||||
mail.setSubject("Contingência Off-line BP-e");
|
||||
mail.setText(getMensagem(historicoCont));
|
||||
mail.setEmailTo(empresaEmail.getDestinatario());
|
||||
mail.setEmailToCO(EMAIL_COPIA_OCULTA);
|
||||
mail.send();
|
||||
}
|
||||
|
||||
private String getMensagem(LogHistoricoContingencia historicoContingencia) {
|
||||
StringBuilder mensagem = new StringBuilder();
|
||||
mensagem.append(String.format("A empresa %s está com a emissão do BP-e em contingência off-line para a UF %s no ambiente de %s. ",
|
||||
historicoContingencia.getEmpresa().getNombempresa(), historicoContingencia.getEstado().getCveestado(),
|
||||
EAmbienteContingencia.getAmbienteContingencia(historicoContingencia.getAmbiente()).getDescricao()));
|
||||
mensagem.append("A emissão em contingência deve ser tratada como exceção, sendo que a regra deve ser a emissão com autorização em tempo real.");
|
||||
mensagem.append("O Fisco poderá solicitar esclarecimentos, e até mesmo restringir ao contribuinte a utilização da modalidade de contingência off-line, caso seja identificado que o emissor do BP-e utiliza a contingência em demasia e sem justificativa aceitável, quando comparado a outros contribuintes em situação similar.");
|
||||
mensagem.append("Na utilização de contingência off-line, o contribuinte assume o risco de perda da informação dos ");
|
||||
mensagem.append("BP-e emitidos em contingência, até que os mesmos constem da base de dados do Fisco.");
|
||||
return mensagem.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -17,8 +17,10 @@ import javax.mail.BodyPart;
|
|||
import javax.mail.Message;
|
||||
import javax.mail.MessagingException;
|
||||
import javax.mail.Multipart;
|
||||
import javax.mail.SendFailedException;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.AddressException;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeBodyPart;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
|
@ -26,13 +28,15 @@ import javax.mail.internet.MimeMultipart;
|
|||
import javax.mail.util.ByteArrayDataSource;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.rjconsultores.ventaboletos.enums.MimeType;
|
||||
import com.rjconsultores.ventaboletos.enums.TypeContentEmail;
|
||||
|
||||
public class SendMail {
|
||||
private static Logger log = LoggerFactory.getLogger(SendMail.class);
|
||||
|
||||
public class SendMail implements java.io.Serializable {
|
||||
private static final String ENCODE_UTF_8 = "UTF-8";
|
||||
|
||||
private static final long serialVersionUID = 2067442255080001075L;
|
||||
|
||||
private String smtpHost;
|
||||
private String smtpUser;
|
||||
|
@ -43,12 +47,12 @@ public class SendMail {
|
|||
private String emailToCO;
|
||||
private List<String> emailCopy = new ArrayList<String>();
|
||||
private String localhost;
|
||||
private String auth;
|
||||
private Boolean auth;
|
||||
private String subject;
|
||||
private String text;
|
||||
private Map<String, ByteArrayOutputStream> anexosBytes;
|
||||
private Map<String, String> anexosArquivos;
|
||||
private Map<String, com.rjconsultores.ventaboletos.enums.MimeType> mimeTypes;
|
||||
private Map<String, MimeType> mimeTypes;
|
||||
|
||||
public SendMail(){
|
||||
this.smtpHost = "";
|
||||
|
@ -57,14 +61,14 @@ public class SendMail {
|
|||
this.smtpPort = "";
|
||||
this.emailFrom = "";
|
||||
this.localhost = "";
|
||||
this.auth = "true";
|
||||
this.auth = true;
|
||||
this.emailTo = "";
|
||||
this.emailToCO = "";
|
||||
}
|
||||
|
||||
public SendMail(String smtpHost, String smtpUser, String smtpPassword, String smtpPort,
|
||||
String emailFrom, String emailTo, List<String> emailCopy, String localhost,
|
||||
String auth, String subject, String text) {
|
||||
Boolean auth, String subject, String text) {
|
||||
this.smtpHost = smtpHost;
|
||||
this.smtpUser = smtpUser;
|
||||
this.smtpPassword = smtpPassword;
|
||||
|
@ -86,96 +90,115 @@ public class SendMail {
|
|||
return removed.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public void send() {
|
||||
public void send() throws SendFailedException {
|
||||
send(null);
|
||||
}
|
||||
|
||||
public void send(TypeContentEmail type) throws SendFailedException {
|
||||
try {
|
||||
String[] to = {};
|
||||
String[] bcc = {};
|
||||
|
||||
if (emailTo.contains(";")){
|
||||
to = emailTo.split(";");
|
||||
} else if (!StringUtils.isBlank(emailTo)){
|
||||
to = new String[1];
|
||||
to[0] = emailTo;
|
||||
}
|
||||
|
||||
if (emailToCO.contains(";")){
|
||||
bcc = emailToCO.split(";");
|
||||
} else if (!StringUtils.isBlank(emailToCO)){
|
||||
bcc = new String[1];
|
||||
bcc[0] = emailToCO;
|
||||
}
|
||||
String[] to = removeNull(getArrayEnderecoEmail(emailTo));
|
||||
String[] bcc = removeNull(getArrayEnderecoEmail(emailToCO));
|
||||
|
||||
to = removeNull(to);
|
||||
bcc = removeNull(bcc);
|
||||
|
||||
Boolean vAuth = (auth == null ? Boolean.TRUE : Boolean.valueOf(auth));
|
||||
|
||||
Properties props = System.getProperties();
|
||||
props.put("mail.smtp.host", smtpHost);
|
||||
|
||||
if (localhost != null) {
|
||||
props.put("mail.smtp.localhost", localhost);
|
||||
}
|
||||
|
||||
if (vAuth) {
|
||||
props.setProperty("mail.smtp.starttls.enable", "true");
|
||||
props.setProperty("mail.smtp.auth", "true");
|
||||
}
|
||||
|
||||
props.setProperty("mail.smtp.port", smtpPort);
|
||||
props.setProperty("mail.smtp.user", smtpUser);
|
||||
|
||||
Session session = Session.getInstance(props, null);
|
||||
Session session = Session.getInstance(getProperties(), null);
|
||||
|
||||
Message message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(emailFrom));
|
||||
|
||||
InternetAddress[] toAddress = new InternetAddress[to.length];
|
||||
|
||||
for (int i = 0; i < to.length; i++) {
|
||||
toAddress[i] = new InternetAddress(to[i]);
|
||||
}
|
||||
|
||||
message.setRecipients(Message.RecipientType.TO, toAddress);
|
||||
|
||||
InternetAddress[] toBccAddress = new InternetAddress[bcc.length];
|
||||
|
||||
for (int i = 0; i < bcc.length; i++) {
|
||||
toBccAddress[i] = new InternetAddress(bcc[i]);
|
||||
}
|
||||
|
||||
message.setRecipients(Message.RecipientType.BCC, toBccAddress);
|
||||
|
||||
InternetAddress[] copyAddress = new InternetAddress[emailCopy.size()];
|
||||
int i = 0;
|
||||
for (String eCopy : emailCopy) {
|
||||
copyAddress[i] = new InternetAddress(eCopy);
|
||||
i++;
|
||||
}
|
||||
message.setRecipients(Message.RecipientType.TO, getInternetAddress(to));
|
||||
message.setRecipients(Message.RecipientType.BCC, getInternetAddress(bcc));
|
||||
InternetAddress[] copyAddress = getInternetAddress(new String[emailCopy.size()]);
|
||||
if (copyAddress.length > 0) {
|
||||
message.setRecipients(Message.RecipientType.CC, copyAddress);
|
||||
}
|
||||
|
||||
message.setSubject(subject);
|
||||
|
||||
BodyPart messageBodyPart = new MimeBodyPart();
|
||||
messageBodyPart.setText(text);
|
||||
((MimeMessage) message).setSubject(subject, ENCODE_UTF_8);
|
||||
|
||||
Multipart multipart = new MimeMultipart();
|
||||
multipart.addBodyPart(messageBodyPart);
|
||||
multipart.addBodyPart(type == null ? getMimeBodyPart() : getMimeBodyPart(type));
|
||||
message.setContent(multipart);
|
||||
|
||||
|
||||
adicionarAnexos(multipart);
|
||||
|
||||
|
||||
Transport t = session.getTransport("smtp");
|
||||
t.connect(smtpUser, smtpPassword);
|
||||
if (auth) {
|
||||
t.connect(smtpUser, smtpPassword);
|
||||
} else {
|
||||
t.connect();
|
||||
|
||||
}
|
||||
t.sendMessage(message, message.getAllRecipients());
|
||||
t.close();
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
throw new SendFailedException("Ocorreu um erro no envio do email.", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String[] getArrayEnderecoEmail(String emailValue) {
|
||||
String[] arrayEmail = {};
|
||||
if (emailValue.contains(";")){
|
||||
arrayEmail = emailValue.split(";");
|
||||
} else if (!StringUtils.isBlank(emailValue)){
|
||||
arrayEmail = new String[1];
|
||||
arrayEmail[0] = emailValue;
|
||||
}
|
||||
return arrayEmail;
|
||||
}
|
||||
|
||||
public void addAnexo(String nome, ByteArrayOutputStream anexo, MimeType mimeType) {
|
||||
if(anexosBytes == null) {
|
||||
anexosBytes = new HashMap<String, ByteArrayOutputStream>();
|
||||
}
|
||||
if(mimeTypes == null) {
|
||||
mimeTypes = new HashMap<String, MimeType>();
|
||||
}
|
||||
anexosBytes.put(nome, anexo);
|
||||
mimeTypes.put(nome, mimeType);
|
||||
}
|
||||
|
||||
public void addAnexo(String nome, String anexo) {
|
||||
if(anexosArquivos== null) {
|
||||
anexosArquivos = new HashMap<String, String>();
|
||||
}
|
||||
anexosArquivos.put(nome, anexo);
|
||||
}
|
||||
|
||||
private BodyPart getMimeBodyPart() throws MessagingException {
|
||||
BodyPart messageBodyPart = new MimeBodyPart();
|
||||
((MimeBodyPart)messageBodyPart).setText(text, ENCODE_UTF_8);
|
||||
return messageBodyPart;
|
||||
}
|
||||
|
||||
private BodyPart getMimeBodyPart(TypeContentEmail type) throws MessagingException {
|
||||
BodyPart messageBodyPart = new MimeBodyPart();
|
||||
messageBodyPart.setContent(text, type.valor);
|
||||
return messageBodyPart;
|
||||
}
|
||||
|
||||
private InternetAddress[] getInternetAddress(String[] address) throws AddressException {
|
||||
InternetAddress[] toAddress = new InternetAddress[address.length];
|
||||
for (int i = 0; i < address.length; i++) {
|
||||
toAddress[i] = new InternetAddress(address[i]);
|
||||
}
|
||||
return toAddress;
|
||||
}
|
||||
|
||||
private Properties getProperties() {
|
||||
Properties props = System.getProperties();
|
||||
props.put("mail.smtp.host", smtpHost);
|
||||
|
||||
if (localhost != null) {
|
||||
props.put("mail.smtp.localhost", localhost);
|
||||
}
|
||||
|
||||
if (auth) {
|
||||
props.setProperty("mail.smtp.starttls.enable", "true");
|
||||
props.setProperty("mail.smtp.user", smtpUser);
|
||||
}
|
||||
|
||||
props.setProperty("mail.smtp.auth", auth.toString());
|
||||
props.setProperty("mail.smtp.port", smtpPort);
|
||||
return props;
|
||||
}
|
||||
|
||||
private void adicionarAnexos(Multipart multipart) throws MessagingException, IOException {
|
||||
anexarArquivosBytes(multipart);
|
||||
anexarArquivos(multipart);
|
||||
|
@ -185,7 +208,7 @@ public class SendMail {
|
|||
if(anexosBytes != null) {
|
||||
for (Entry<String, ByteArrayOutputStream> anexo : anexosBytes.entrySet()) {
|
||||
BodyPart bodyPart = new MimeBodyPart();
|
||||
com.rjconsultores.ventaboletos.enums.MimeType mimeType = mimeTypes.get(anexo.getKey());
|
||||
MimeType mimeType = mimeTypes.get(anexo.getKey());
|
||||
DataSource bds = new ByteArrayDataSource(new ByteArrayInputStream(anexo.getValue().toByteArray()), mimeType.toString());
|
||||
bodyPart.setDataHandler(new DataHandler(bds));
|
||||
bodyPart.setFileName(anexo.getKey());
|
||||
|
@ -295,22 +318,19 @@ public class SendMail {
|
|||
this.emailToCO = emailToCO;
|
||||
}
|
||||
|
||||
public void addAnexo(String nome, ByteArrayOutputStream anexo, MimeType mimeType) {
|
||||
if(anexosBytes == null) {
|
||||
anexosBytes = new HashMap<String, ByteArrayOutputStream>();
|
||||
}
|
||||
if(mimeTypes == null) {
|
||||
mimeTypes = new HashMap<String, MimeType>();
|
||||
}
|
||||
anexosBytes.put(nome, anexo);
|
||||
mimeTypes.put(nome, mimeType);
|
||||
public Boolean getAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
public void addAnexo(String nome, String anexo) {
|
||||
if(anexosArquivos== null) {
|
||||
anexosArquivos = new HashMap<String, String>();
|
||||
}
|
||||
anexosArquivos.put(nome, anexo);
|
||||
|
||||
public void setAuth(Boolean auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public Map<String, String> getAnexosArquivos() {
|
||||
return anexosArquivos;
|
||||
}
|
||||
|
||||
public void setAnexosArquivos(Map<String, String> anexosArquivos) {
|
||||
this.anexosArquivos = anexosArquivos;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue