通过 smtp.gmail 在 Spring Faremework 中发送电子邮件

Send email via smtp.gmail in Spring Faremework

我正在 Spring 启动时通过 smtp.gmail 发送电子邮件。

EmailConfig.java

@Configuration
public class EmailConfig
{
    @Bean
    public JavaMailSender getJavaMailSender()
    {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(25);

        mailSender.setUsername("abc@gmail.com");
        mailSender.setPassword("123");

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");

        return mailSender;
    }

    @Bean
    public SimpleMailMessage emailTemplate()
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo("abc@gmail.com");
        message.setFrom("johndoe@gmail.com");
        message.setText("FATAL - Application crash. Save your job !!");
        return message;
    }
}

SendEmailService.java

@Service("emailService")
public class SendEmailService {

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    private SimpleMailMessage preConfiguredMessage;

    public void sendPreConfiguredMail(String message)
    {
        SimpleMailMessage mailMessage = new SimpleMailMessage(preConfiguredMessage);
        mailMessage.setText(message);
        mailSender.send(mailMessage);
    }
}

Error : I have received an email on my account "Sign-in attempt was blocked" Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access

如何解决这个问题。

只需转到您的帐户安全并允许安全性较低的应用 "ON"

  1. 前往 gmail.com
  2. 单击您的个人资料图片并转到 管理您的帐户
  3. 在新页面上,转到“安全”选项卡
  4. 向下滚动并开启安全性较低的应用访问
  5. 在您的电子邮件中确认访问权限(可选,有时仅需要)

Google 更改了一些执行此操作的方法,因此现在您可以为您的应用添加一个“特殊”密码。

  1. 前往管理您的帐户
  2. 转到安全
  3. 向下滚动并找到“登录您的 Google 帐户”
  4. 转到“应用程序密码”

在此页面上,您可以创建一个唯一的通行证,需要用于通过应用程序登录您的acc。