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

前端 未结 6 2038
傲寒
傲寒 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:40

    This was driving me crazy and so just wanted to add what worked for me. I had to update my version of JavaMail (1.4.5) for this to work - not sure what version was being used before.

    Once I updated to new version of JavaMail, the following code worked for me (can uncomment the debug lines to get additional debugging info - port was 587 and host was smtp.gmail.com):

    public void sendMailWithAuth(String host, String user, String password, 
        String port, List toList, String htmlBody, 
            String subject) throws Exception {
    
        Properties props = System.getProperties();
    
        props.put("mail.smtp.user",user); 
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.host", host); 
        props.put("mail.smtp.port", port); 
        //props.put("mail.debug", "true"); 
        props.put("mail.smtp.auth", "true"); 
        props.put("mail.smtp.starttls.enable","true"); 
        props.put("mail.smtp.EnableSSL.enable","true");
    
        Session session = Session.getInstance(props, null);
        //session.setDebug(true);
    
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(user));
    
        // To get the array of addresses
        for (String to: toList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
    
        message.setSubject(subject);
        message.setContent(htmlBody, "text/html");
    
        Transport transport = session.getTransport("smtp");
        try {
            transport.connect(host, user, password);
            transport.sendMessage(message, message.getAllRecipients());
        } finally {
            transport.close();
        }
    }
    

提交回复
热议问题