请求处理失败;邮件服务器连接失败,无法连接到主机,端口:smtp.gmail.com,25;超时-1;

发布于 2025-02-06 16:26:24 字数 5461 浏览 1 评论 0原文

当我尝试使用authcontroller.java类发送电子邮件时,如何解决错误?

在不同项目中仅使用电子邮件服务时,它正常工作,但是当我将其与主要项目集成在一起时,它无法正常工作。

org.springframework.mail.mailsendexception:邮件服务器连接失败;嵌套例外是com.sun.mail.util.mailconnectexception:无法连接到主机,端口:smtp.gmail.com,25;超时-1;嵌套的例外是:java.net.connectException:连接时间:

authcontroller.java class



@CrossOrigin("*")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

@Autowired
private UserRepo userRepo;
@Autowired
private RoleRepo roleRepo;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtUtils jwtUtils;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired 
private EmailService emailService;

// POST request for adding user
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupRequest) {
if (userRepo.existsByEmail(signupRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}

User user = new User(signupRequest.getEmail(),
signupRequest.getName(),
passwordEncoder.encode(signupRequest.getPassword()),
signupRequest.getAddress());
//signupRequest.setRole(new ArraySet<>(Set.of("ROLE_USER","")));
signupRequest.setRole("ROLE_ADMIN");
String strRoles = signupRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles==null) {
Role userRole = roleRepo.findByRoleName("ROLE_ADMIN")
.orElseThrow(()-> new RuntimeException("Error: role not found"));
roles.add(userRole);
}
user.setRoles(roles);
userRepo.save(user);
String emailId = user.getEmail();
emailService.sendTextEmail(emailId);
return ResponseEntity
.status(201)
.body(new MessageResponse("User created successfully"));
}


// POST request for validating user
@PostMapping("/authenticate")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(),
loginRequest.getPassword()));

SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateToken(authentication);
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetailsImpl.getAuthorities()
.stream()
.map(i->i.getAuthority())
.collect(Collectors.toList());

return ResponseEntity.ok(new JwtResponse(jwt,
userDetailsImpl.getId(),
userDetailsImpl.getEmail(),
roles));
}

@GetMapping("/")
public ResponseEntity<?> getUser() {
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
Long id = userDetailsImpl.getId();
Optional<User> optional = userRepo.findById(id);
return ResponseEntity.ok(optional.get());
}
}

user.java class


@Setter
@Getter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
//@AllArgsConstructor
@Entity
@Table(name = "`user`", uniqueConstraints = {@UniqueConstraint(columnNames = "email")})
public class User {

    public User(String email, String name, String password, String address) {
        this.email = email;
        this.name = name;
        this.password = password;
        this.address = address;
    }

    @Id
    @Column(name = "userId")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    @Size(max = 50)
    @Email
    private String email;
    @Size(max = 50)
    @NotBlank
    private String name;
    @Size(max = 100)
    @NotBlank
    private String password;
    @Size(max = 50)
    @NotBlank
    private String address;
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "cart", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name  = "foodId"))
    private List<Food> cart = new ArrayList<Food>();
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name  = "roleId"))
    private Set<Role> roles = new HashSet<Role>();
    
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "orders", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name = "orderId"))
    private List<Order> orders = new ArrayList<Order>();

}

emailserviceimpl.java class i


    @Service
    public class EmailServiceImpl implements EmailService {
    
        private static final Logger logger = LoggerFactory
                .getLogger(EmailServiceImpl.class);
        @Autowired
        private JavaMailSender javaMailSender;
    
        @Override
        //Sending User Object
        public void sendTextEmail(String mail) {
            logger.info("Simple Email sending start");
    
            SimpleMailMessage simpleMessage = new SimpleMailMessage();
            simpleMessage.setTo(mail); //Enter customer email 
            simpleMessage.setSubject("User Registration");
            simpleMessage.setText("Dear customer welcome to hungerbuddy.");
            javaMailSender.send(simpleMessage);
            logger.info("Simple Email sent");
    
        }
    }

删除了我的emailID和密码后,我添加了属性文件的图像。

谢谢

How to resolve the error when I am trying to send email using authcontroller.java class?

When I am using email service alone in different project it is working properly but when I integrated it with my main project it is not working.

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 25; timeout -1; nested exception is:java.net.ConnectException: Connection timed out:

AuthController.java Class



@CrossOrigin("*")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

@Autowired
private UserRepo userRepo;
@Autowired
private RoleRepo roleRepo;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtUtils jwtUtils;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired 
private EmailService emailService;

// POST request for adding user
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupRequest) {
if (userRepo.existsByEmail(signupRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}

User user = new User(signupRequest.getEmail(),
signupRequest.getName(),
passwordEncoder.encode(signupRequest.getPassword()),
signupRequest.getAddress());
//signupRequest.setRole(new ArraySet<>(Set.of("ROLE_USER","")));
signupRequest.setRole("ROLE_ADMIN");
String strRoles = signupRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles==null) {
Role userRole = roleRepo.findByRoleName("ROLE_ADMIN")
.orElseThrow(()-> new RuntimeException("Error: role not found"));
roles.add(userRole);
}
user.setRoles(roles);
userRepo.save(user);
String emailId = user.getEmail();
emailService.sendTextEmail(emailId);
return ResponseEntity
.status(201)
.body(new MessageResponse("User created successfully"));
}


// POST request for validating user
@PostMapping("/authenticate")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(),
loginRequest.getPassword()));

SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateToken(authentication);
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetailsImpl.getAuthorities()
.stream()
.map(i->i.getAuthority())
.collect(Collectors.toList());

return ResponseEntity.ok(new JwtResponse(jwt,
userDetailsImpl.getId(),
userDetailsImpl.getEmail(),
roles));
}

@GetMapping("/")
public ResponseEntity<?> getUser() {
UserDetailsImpl userDetailsImpl = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
Long id = userDetailsImpl.getId();
Optional<User> optional = userRepo.findById(id);
return ResponseEntity.ok(optional.get());
}
}

User.java Class


@Setter
@Getter
@EqualsAndHashCode
@ToString
@NoArgsConstructor
//@AllArgsConstructor
@Entity
@Table(name = "`user`", uniqueConstraints = {@UniqueConstraint(columnNames = "email")})
public class User {

    public User(String email, String name, String password, String address) {
        this.email = email;
        this.name = name;
        this.password = password;
        this.address = address;
    }

    @Id
    @Column(name = "userId")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    @Size(max = 50)
    @Email
    private String email;
    @Size(max = 50)
    @NotBlank
    private String name;
    @Size(max = 100)
    @NotBlank
    private String password;
    @Size(max = 50)
    @NotBlank
    private String address;
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "cart", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name  = "foodId"))
    private List<Food> cart = new ArrayList<Food>();
    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name  = "roleId"))
    private Set<Role> roles = new HashSet<Role>();
    
    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "orders", joinColumns = @JoinColumn(name = "userId"),
    inverseJoinColumns = @JoinColumn(name = "orderId"))
    private List<Order> orders = new ArrayList<Order>();

}

EmailServiceImpl.java Class


    @Service
    public class EmailServiceImpl implements EmailService {
    
        private static final Logger logger = LoggerFactory
                .getLogger(EmailServiceImpl.class);
        @Autowired
        private JavaMailSender javaMailSender;
    
        @Override
        //Sending User Object
        public void sendTextEmail(String mail) {
            logger.info("Simple Email sending start");
    
            SimpleMailMessage simpleMessage = new SimpleMailMessage();
            simpleMessage.setTo(mail); //Enter customer email 
            simpleMessage.setSubject("User Registration");
            simpleMessage.setText("Dear customer welcome to hungerbuddy.");
            javaMailSender.send(simpleMessage);
            logger.info("Simple Email sent");
    
        }
    }

I have added the image of properties file after removing my emailId and password.

ThankYou

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文