JavaMail中的会话

时间:2017-07-20 11:30:36

标签: java session authentication javamail

在会话对象(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);
          }
       }

1 个答案:

答案 0 :(得分:1)

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