Must issue a STARTTLS command first. Sending email with Java and Google Apps

前端 未结 6 2042
傲寒
傲寒 2020-11-30 05:56

I am trying to use Bill the Lizard\'s code to send an email using Google Apps. I am getting this error:

Exception in thread \"main\" javax.mail.SendFailedEx         


        
6条回答
  •  我在风中等你
    2020-11-30 06:22

    I think it's got to do with using SMTPS instead of SMTP for mail transport. Here's a different version, modeled after the JavaMail FAQ on accessing Gmail. Note that I have left out all of the finer level exception handling for clarity.

    private static void send(
            final String username,
            final String password,
            final String recipients,
            final String subject,
            final String body)
            throws Exception
    {
        final Session session = Session.getInstance(System.getProperties(), null);
        final Message msg = new MimeMessage(session);
        final String senderEmail = username.contains("@") ? username : (username + "@gmail.com");
        msg.setFrom(new InternetAddress(senderEmail));
    
        final Address[] recipientAddresses = InternetAddress.parse(recipients);
        msg.setRecipients(Message.RecipientType.TO, recipientAddresses);
    
        msg.setSentDate(new Date());
        msg.setSubject(subject);
        msg.setText(body);
    
        final Transport transport = session.getTransport("smtps");
        transport.connect(GMAIL_SMTP_HOST, GMAIL_SMTP_PORT, username, password);
        transport.sendMessage(msg, recipientAddresses);
        transport.close();
    }
    

提交回复
热议问题