【问题标题】:Session in JavaMailJavaMail 中的会话
【发布时间】:2017-07-20 19:40:31
【问题描述】:

在会话对象(PasswordAuthentication ) 中的以下代码中,我们必须提供什么用户名和密码才能发送邮件?发件人的用户名密码或收件人的凭据? 我真的很困惑,我正在使用 java Mail 发送邮件

public void sendMail(String email,String token)
    {
        // Recipient's email ID needs to be mentioned.
           String to = email;
          // Sender's email ID needs to be mentioned
          // Assuming you are sending email through relay.jangosmtp.net
          String host = "smtp.gmail.com";
          Properties props = new Properties();
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.starttls.enable", "true");
          props.put("mail.smtp.host", host);
          props.put("mail.smtp.port", "587");

          // Get the Session object.
          Session session = Session.getInstance(props,
             new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(username, password);
           }
             });

          try {
           // Create a default MimeMessage object.
           Message message = new MimeMessage(session);

           // Set From: header field of the header.
           message.setFrom(new InternetAddress("Issme-Customer-Service"));

           // Set To: header field of the header.
           message.setRecipients(Message.RecipientType.TO,
                   InternetAddress.parse(to));

          message.setSubject("Email Verification Of issme Account");

            message.setContent(
                    "<h2>Email Verification </h2>" + 
                    "<h3> Please goto  the following URL to verify your ISSME account\n </h3> " +
                     token , "text/html; charset=utf-8");


           // Send message
           Transport.send(message);

           System.out.println("Sent message successfully....");

          } catch (MessagingException e) {
             throw new RuntimeException(e);
          }
       }

【问题讨论】:

  • 为什么会是接收方的凭据?这是发件人的用户名和密码,就像您在邮件客户端中设置的一样。
  • 如果这是一个 Web 应用程序,最好在应用程序服务器中设置一个 JavaMail 会话。与外部服务的连接是一个部署环境问题,它们的参数不应被硬编码。
  • 您需要设置可以向 SMTP 服务器(发件人)进行身份验证的凭据

标签: java session authentication jakarta-mail


【解决方案1】:

您需要发送发件人的凭据,gmail 的 SMTP 服务器将对其进行身份验证,然后它将发送电子邮件。

【讨论】:

  • 好的,如果我在数据库中有表单详细信息,并且想从代码中获取电子邮件中的详细信息,我该怎么做?表示没有具有凭据的发件人
  • 首先你不应该在你的数据库中直接拥有密码。但是您无论如何都可以查询数据库并使用该信息发送电子邮件。
  • 消息必须来自“某人”。那个“某人”必须在邮件服务器上有一个帐户。您的程序需要该“某人”的凭据,以便您可以登录到邮件服务器并发送消息。
猜你喜欢
  • 2019-02-02
  • 2021-05-20
  • 1970-01-01
  • 2011-05-19
  • 2017-06-17
  • 2012-09-06
  • 2013-08-26
  • 2011-02-12
  • 2015-03-18
相关资源
最近更新 更多