在Java中使用Gmail发送邮件

以下Java代码可以实现使用SMTP登陆到Gmail中并使用Gmail发送邮件。

使用Gmail发送邮件的代码:

 
 
 
  1. String host = "smtp.gmail.com";  
  2.     String from = "username";  
  3.     String pass = "password";  
  4.     Properties props = System.getProperties();  
  5.     props.put("mail.smtp.starttls.enable""true"); // 在本行添加  
  6.     props.put("mail.smtp.host", host);  
  7.     props.put("mail.smtp.user", from);  
  8.     props.put("mail.smtp.password", pass);  
  9.     props.put("mail.smtp.port""587");  
  10.     props.put("mail.smtp.auth""true");  
  11.  
  12.     String[] to = {"[email protected]"}; // 在本行添加  
  13.  
  14.     Session session = Session.getDefaultInstance(props, null);  
  15.     MimeMessage message = new MimeMessage(session);  
  16.     message.setFrom(new InternetAddress(from));  
  17.  
  18.     InternetAddress[] toAddress = new InternetAddress[to.length];  
  19.  
  20.     // 获取地址的array  
  21.     forint i=0; i < to.length; i++ ) { // 从while循环更改而成  
  22.         toAddress[i] = new InternetAddress(to[i]);  
  23.     }  
  24.     System.out.println(Message.RecipientType.TO);  
  25.  
  26.     forint i=0; i < toAddress.length; i++) { // 从while循环更改而成  
  27.         message.addRecipient(Message.RecipientType.TO, toAddress[i]);  
  28.     }  
  29.     message.setSubject("sending in a group");  
  30.     message.setText("Welcome to JavaMail");  
  31.     Transport transport = session.getTransport("smtp");  
  32.     transport.connect(host, from, pass);  
  33.     transport.sendMessage(message, message.getAllRecipients());  
  34.     transport.close();  
  35.  

代码本身应该很清楚了。在第7和8行加入你的Google账号密码:

 
 
 
  1. props.put("mail.smtp.user", from);  
  2. props.put("mail.smtp.password", pass); 

在12行加入收件人信息:

 
 
 
  1. String[] to = {"[email protected]"}; // 在本行添加  

这样就可以在你的Java程序中使用Gmail发送邮件啦。

【编辑推荐】

  1. Facebook启用OpenID可用Gmail账号登录
  2. Google推出新编程语言Simple 用于Android开发
  3. Google Android开发团队确定Donut代号
  4. Google App Engine的Java SDK 1.2.2发布
  5. 在Google Java App Engine上实现文档存储和搜索
THE END