sqtsqt 发表于 2017-1-9 09:15:00

使用apache mail开源项目发送邮件示例

import org.apache.commons.mail.*;

/**
* 使用apache mail开源项目发送邮件示例
*
* @author www.NetJava.cn
*/
public class ApacheMailSender {
    // 程序主方法
    public static void main(String[] args) throws Exception {
      ApacheMailSender as = new ApacheMailSender();
      String host = "smtp.163.com";
      String from = "xxx@163.com";
      String username = "xxx";
      String password = "xxx";
      // 接收者邮箱
      String to = "yyy@163.com";
      String subject = "apache Mail发送的主题--这是带符件的邮件 成功!";
      String mailConent = "这是apache Mail组件从netjavasender发送带符件邮件内容,你能看到符件吗? ";
      // 调用发送附件邮件方法
      as.sendAttachmentMail(host, from, username, password, to, subject,
                mailConent);
    }

    /**
   * 通过Apache Mail组件带符件的邮件发送方法
   *
   * @param host
   *            :发送时所使用的smtp服务器
   * @param from
   *            : 发送者名字
   * @param username
   *            : 发送者登陆服务器时的用户名
   * @param password
   *            : 发送者登陆服务器时的密码
   * @param to
   *            :接收者邮箱
   * @param subject
   *            : 邮件主题
   * @param mailConent
   *            :邮件内容
   * @return :是否发送成功
   */
    public boolean sendAttachmentMail(String host, String from,
            String username, String password, String to, String subject,
            String mailConent) throws Exception {
      // 创建附件对象
      EmailAttachment attachment = new EmailAttachment();
      /* 附件的地址 */
      attachment.setPath("C:/osinfo.ini");
      // 设定为附件
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      /* 附件的描述 */
      attachment.setDescription("jPortMap项目设计附件文档");
      /* 附件的名称,必须和文件名一致 */
      attachment.setName("osinfo.ini");
      /* new一个HtmlEmail发送对象 */
      HtmlEmail email = new HtmlEmail();
      email.setAuthentication(username, password);
      email.setHostName(host);
      email.addTo(to, from);
      email.setFrom(from);
      email.setSubject(subject);
      // 注意,发送内容时,后面这段会让中文正常显示,否则乱码
      email.setCharset("GB2312");
      email.setTextMsg(mailConent);
      email.setHtmlMsg("<html>这是封测试附件邮件</html>"); /* 邮件内容 */
      // 添加附件对象
      email.attach(attachment);
      // 发送
      email.send();
      System.out.println("带符件的邮件发送成功!");
      return true;

    }
}
页: [1]
查看完整版本: 使用apache mail开源项目发送邮件示例