手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

在Java中使用Gmail发送邮件

[日期:2009-08-14] 来源:IT专家网  作者:Java编辑 [字体:大 中 小]
以下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 = {"to@gmail.com"}; // 在本行添加

    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 = {"to@gmail.com"}; // 在本行添加

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

linux
相关资讯       Java 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款