我有 dropwizard REST 服务,我正在尝试在用户注册后发送验证电子邮件链接/代码。
我的数据库中的用户表中有一个名为 is_active 的字段,它表示用户是否已通过验证。
private String email;
@JsonProperty
private String password;
@JsonProperty
private String name;
@JsonProperty
private String surname;
@JsonProperty
private boolean isActive;
我试图找出发送此验证电子邮件的正确方法,我编写了一个向用户发送 SMTP 电子邮件的类,但我有点怀疑它发送电子邮件的正确方法是否正确?
public class SendEmail
{
public static void main(String [] args){
String to = "customer@gmail.com";
String from = "mycompany@gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("verification email");
message.setText("Hello, this is sample verification email ");
Transport.send(message);
System.out.println("message sent successfully....");
}catch (MessagingException mex) {mex.printStackTrace();}
}
}
这是我应该如何实现或使用一些外部提供程序,如 sendgrid为此?
最佳答案
你的方法很好。需要考虑的一些事项:
- SMTP 服务器在哪个时间范围内接受多少封电子邮件?某些 SMPT 服务器应用速率限制,这可能会导致消息发送失败。您的代码应该认识到这一点,并制定一个策略,以便稍后重新发送电子邮件。
- 电子邮件正文中的验证链接应包含只能用于验证特定用户的唯一 key 。该 secret 必须被存储并与用户关联。
- 链接不应包含用户 ID 或名称等内容。此类链接很容易被伪造。
- 通过点击验证链接调用的 REST API 应获取 secret 并查找与其关联的用户。
关于java - 从 java REST 服务发送验证码/链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57717201/