在Java中使用Gmail发送邮件
以下Java代码可以实现使用SMTP登陆到Gmail中并使用Gmail发送邮件。
使用Gmail发送邮件的代码:
- String host = "smtp.gmail.com";
- String from = "username";
- String pass = "password";
- Properties props = System.getProperties();
- props.put("mail.smtp.starttls.enable", "true"); // 在本行添加
- props.put("mail.smtp.host", host);
- props.put("mail.smtp.user", from);
- props.put("mail.smtp.password", pass);
- props.put("mail.smtp.port", "587");
- props.put("mail.smtp.auth", "true");
- String[] to = {"[email protected]"}; // 在本行添加
- Session session = Session.getDefaultInstance(props, null);
- MimeMessage message = new MimeMessage(session);
- message.setFrom(new InternetAddress(from));
- InternetAddress[] toAddress = new InternetAddress[to.length];
- // 获取地址的array
- for( int i=0; i < to.length; i++ ) { // 从while循环更改而成
- toAddress[i] = new InternetAddress(to[i]);
- }
- System.out.println(Message.RecipientType.TO);
- for( int i=0; i < toAddress.length; i++) { // 从while循环更改而成
- message.addRecipient(Message.RecipientType.TO, toAddress[i]);
- }
- message.setSubject("sending in a group");
- message.setText("Welcome to JavaMail");
- Transport transport = session.getTransport("smtp");
- transport.connect(host, from, pass);
- transport.sendMessage(message, message.getAllRecipients());
- transport.close();
代码本身应该很清楚了。在第7和8行加入你的Google账号密码:
- props.put("mail.smtp.user", from);
- props.put("mail.smtp.password", pass);
在12行加入收件人信息:
- String[] to = {"[email protected]"}; // 在本行添加
这样就可以在你的Java程序中使用Gmail发送邮件啦。
【编辑推荐】
- Facebook启用OpenID可用Gmail账号登录
- Google推出新编程语言Simple 用于Android开发
- Google Android开发团队确定Donut代号
- Google App Engine的Java SDK 1.2.2发布
- 在Google Java App Engine上实现文档存储和搜索
版权声明:
作者:后浪云
链接:https://www.idc.net/help/404399/
文章版权归作者所有,未经允许请勿转载。
THE END