Error sending an email

0

Mail Class that sends the mail

package com.example.demo.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.stereotype.Controller;

public class Mail {
    @Autowired
    private JavaMailSender sender;

    public void sendEmail(String to, String subject, String text) {
                SimpleMailMessage message = new SimpleMailMessage(); 
                message.setTo(to); 
                message.setSubject(subject); 
                message.setText(text);
                sender.send(message);

            }
}

Action of registro in controller UsuarioController

Mail mail;
@RequestMapping(value = "/registro", method = RequestMethod.POST)
    public String registroPost(@RequestParam("alias") String alias,
            @RequestParam("contrasena") String contrasena,
            @RequestParam("nombre") String nombre,
            @RequestParam("primerApellido") String primerApellido,
            @RequestParam("segundoApellido") String segundoApellido,
            @RequestParam("telefono") String telefono,
            @RequestParam("email") String email,
            @RequestParam("sexo") String sexo,
            ModelMap m)  {


        Rol rolPorDefecto = (Rol) repoRol.getDefaultRol();
        Usuario u = new Usuario(alias, contrasena, nombre, primerApellido, segundoApellido, telefono, email, sexo, rolPorDefecto);
        try {    
            if (repoUsuario.datosPerfil(alias) != null) {
                m.put("view", "/_t/error");
            }
        } catch (Exception e) {
            mail.sendEmail(email, "Bienvenido", "Bienvenido a la web");
            m.put("alias", alias);
            m.put("view", "/usuario/crearPost");
            repoUsuario.save(u);
        }
        return "views/_t/main";
            }

The problem is that I get the following error when I want to send the mail

java.lang.NullPointerException: null
    at com.example.demo.controllers.UsuarioController.registroPost(UsuarioController.java:64) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
    
asked by Stewie 22.11.2018 в 21:31
source

1 answer

1

Apparently your error is because you are not properly instantiating or injecting your class Mail .

You could add the @Service annotation to your class in the following way:

@Service
public class Mail {

And in the class of your controller the annotation @Autowired of the following form:

@Autowired
Mail mail;

References

answered by 22.11.2018 / 22:57
source