Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

Aula 08 - Envio do e-mail

Ao tentar enviar o e-mail conforme a aula ocorre o erro abaixo:

Pagamento efetuado com sucesso
mar 16, 2017 3:32:44 PM org.apache.catalina.core.ApplicationDispatcher invoke
GRAVE: Servlet.service() for servlet dispatcher threw exception
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp
; message exception details (1) are:
Failed message 1:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:424)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
    at br.com.casadocodigo.loja.controllers.PagamentoController.enviaEmailCompraProduto(PagamentoController.java:65)
    at br.com.casadocodigo.loja.controllers.PagamentoController.lambda$0(PagamentoController.java:44)
    at org.springframework.web.context.request.async.WebAsyncManager$4.run(WebAsyncManager.java:322)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

mar 16, 2017 3:32:44 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [dispatcher] in context with path [/casadocodigo] threw exception [Request processing failed; nested exception is org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp
; message exceptions (1) are:
Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp
] with root cause
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp
; message exception details (1) are:
Failed message 1:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. n60sm1426280uan.36 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:424)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
    at br.com.casadocodigo.loja.controllers.PagamentoController.enviaEmailCompraProduto(PagamentoController.java:65)
    at br.com.casadocodigo.loja.controllers.PagamentoController.lambda$0(PagamentoController.java:44)
    at org.springframework.web.context.request.async.WebAsyncManager$4.run(WebAsyncManager.java:322)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Classe PagamentoController .

package br.com.casadocodigo.loja.controllers;

import java.util.concurrent.Callable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import br.com.casadocodigo.loja.models.CarrinhoCompras;
import br.com.casadocodigo.loja.models.DadosPagamento;
import br.com.casadocodigo.loja.models.Usuario;

@RequestMapping("/pagamento")
@Controller
public class PagamentoController {

  @Autowired
  private CarrinhoCompras carrinho;

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private MailSender sender;

  @RequestMapping(value="/finalizar", method=RequestMethod.POST)
  public Callable<ModelAndView> finalizar(@AuthenticationPrincipal Usuario usuario, 
      RedirectAttributes model) {
    return () -> {
      String uri = "http://book-payment.herokuapp.com/payment";

      try {
        String response = restTemplate.postForObject(uri, new DadosPagamento(carrinho.getTotal()), String.class);
        System.out.println(response);

        enviaEmailCompraProduto(usuario);

        model.addFlashAttribute("sucesso", response);
        return new ModelAndView("redirect:/produtos");
      } catch (HttpClientErrorException e) {
        e.printStackTrace();
        model.addFlashAttribute("falha", "Valor maior que o permitido");
        return new ModelAndView("redirect:/produtos");
      }
    };
  }

  private void enviaEmailCompraProduto(Usuario usuario) {
    SimpleMailMessage email = new SimpleMailMessage();

    email.setSubject("Compra finalizada com sucesso");
    //email.setTo(usuario.getEmail());
    email.setTo("lgn200@gmail.com");
    email.setText("Compra aprovada com sucesso no valor de " + carrinho.getTotal());
    email.setFrom("compras@casadocodigo.com.br");

    sender.send(email);
  }

}

Classe AppWebConfiguration .

package br.com.casadocodigo.loja.conf;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.google.common.cache.CacheBuilder;

import br.com.casadocodigo.loja.controllers.HomeController;
import br.com.casadocodigo.loja.daos.ProdutoDAO;
import br.com.casadocodigo.loja.infra.FileSaver;
import br.com.casadocodigo.loja.models.CarrinhoCompras;

@EnableWebMvc
@EnableCaching 
@ComponentScan(basePackageClasses={HomeController.class, ProdutoDAO.class, FileSaver.class, CarrinhoCompras.class})
public class AppWebConfiguration extends WebMvcConfigurerAdapter{

        @Bean
        public InternalResourceViewResolver internalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/views/");
            resolver.setSuffix(".jsp");

            //resolver.setExposeContextBeansAsAttributes(true);
            resolver.setExposedContextBeanNames("carrinhoCompras");
            return resolver;
        }

        @Bean
        public MessageSource messageSource() {
            ReloadableResourceBundleMessageSource messageSource =
                    new ReloadableResourceBundleMessageSource();

            messageSource.setBasename("/WEB-INF/messages");
            messageSource.setDefaultEncoding("UTF-8");
            messageSource.setCacheSeconds(1);

            return messageSource;
        }

        @Bean
        public FormattingConversionService mvcConversionService() {
            DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
            DateFormatterRegistrar registra = new DateFormatterRegistrar();
            registra.setFormatter(new DateFormatter("dd/MM/yyyy"));
            registra.registerFormatters(conversionService);

            return conversionService;

        }

        @Bean
        public MultipartResolver multipartResolver() {
            return new StandardServletMultipartResolver();
        }

        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }

        @Bean
        public CacheManager cacheManager(){
          CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(5, TimeUnit.MINUTES);
          GuavaCacheManager manager = new GuavaCacheManager();
          manager.setCacheBuilder(builder);
          return manager;
        }
        @Bean
        public ViewResolver contentNegotiationViewResolver(ContentNegotiationManager manager){
            List<ViewResolver> viewResolvers = new ArrayList<>();
            viewResolvers.add(internalResourceViewResolver());
            viewResolvers.add(new JsonViewResolver());

            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
            resolver.setViewResolvers(viewResolvers);
            resolver.setContentNegotiationManager(manager);
            return resolver;

        }

        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LocaleChangeInterceptor());
        }

        @Bean
        public LocaleResolver localeResolver(){
            return new CookieLocaleResolver();
        }

        @Bean
        public MailSender mailSender(){
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

            mailSender.setHost("smtp.gmail.com");
            mailSender.setUsername("alura.springmvc@gmail.com");
            mailSender.setPassword("alura2015");
            mailSender.setPort(587);

            Properties mailProperties = new Properties();
            mailProperties.put("mail.smtp.auth", true);
            mailProperties.put("mail.smpt.starttls.enable", true);

            mailSender.setJavaMailProperties(mailProperties);
            return mailSender;
        }
}
2 respostas

O que acho engraçado é que seguir os videos do instrutor sempre ocorrem algum erro que ele consegue fazer funcionar por milagre e nós temos que ficar buscando onde tá o erro e abrindo perguntas no fórum. Os outros cursos que fiz não tinham esse problema.

solução!

Achei a resposta em outro forum.. Faltou nas configurações o

mailProperties.put("mail.smtp.starttls.required",true);