通过java代码发送电子邮件的SMTP异常

时间:2014-11-13 13:56:54

标签: java smtp javamail

我正在尝试使用java发送电子邮件,但我的代码抛出异常 异常herejavax.mail.MessagingException:无法向SMTP主机发送命令;

我正在使用以下代码

 import java.util.Properties;
 import javax.mail.*;
 import javax.mail.internet.*;

 public class SendEmail {

     public static void main(String args[]) {

       final String username ="mymail@gmail.com"; 
       final String password = "password here";

       final String xtomail="email here";
       final String cc="email here";
       final String bcc="email here";

       final String xsub="heavy discount for static websites";
       final String xbody="we are great leader in software industry";

       Properties props = new Properties();

       try{    
           props.put("mail.smtp.auth", "true");
           props.put("mail.smtp.starttls.enable", "true");
           props.put("mail.smtp.host", "smtp.gmail.com");
           props.put("mail.smtp.port", "587");

       } catch(Exception ex) {
           System.out.println("exception here"+ex); 
       }

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

       try {

           Message message = new MimeMessage(session);
           message.setFrom(new InternetAddress(username));
           message.setRecipients(Message.RecipientType.TO,
                                 InternetAddress.parse(xtomail));
           message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(cc));
           message.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(bcc));
           message.setSubject(xsub);
           message.setText(xbody);

           Transport.send(message);
           System.out.println("email send");             
       }
       catch (Exception e) {
           System.out.println("Exception here"+e);
       }                    
    }
}        

1 个答案:

答案 0 :(得分:0)

debug output显示什么?

您的Gmail帐户是否已启用less secure apps