分享

JavaMail发送HTML格式邮件 - AJava

 闪宁斯达 2010-09-20
  1. /**  
  2.   *   
  3.   * @param smtp  
  4.   *            SMTP主机地址  
  5.   * @param port  
  6.   *            SMTP主机地址端口  
  7.   * @param user  
  8.   *            用户名  
  9.   * @param password  
  10.   *            密码  
  11.   * @param from  
  12.   *            发信人  
  13.   * @param to  
  14.   *            收信人  
  15.   * @param cc  
  16.   *            抄送人  
  17.   * @param bcc  
  18.   *            暗送人  
  19.   * @param subject  
  20.   *            主题  
  21.   * @param body  
  22.   *            内容  
  23.   * @throws Exception  
  24.   */  
  25.  public static void send(String smtp, int port, String user,   
  26.    String password, String from, String to, String cc, String bcc,   
  27.    String subject, String body) throws Exception {   
  28.   // 变量声明   
  29.   Properties props = new Properties();// 系统属性   
  30.   // 设置系统属性   
  31.   props.put("mail.transport.protocol""smtp"); // 使用smtp协议   
  32.   props.put("mail.smtp.auth""true"); // 是否需要邮件认证   
  33.   
  34.   // 获得邮件会话对象   
  35.   Session mailSession = Session.getDefaultInstance(props, null);   
  36.   mailSession.setDebug(true);   
  37.   
  38.   // 创建MIME邮件对象   
  39.   MimeMessage mimeMsg = new MimeMessage(mailSession);   
  40.   
  41.   // 设置发信人   
  42.   mimeMsg.setFrom(new InternetAddress(from));   
  43.   // 设置收信人   
  44.   if (to != null) {   
  45.    mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress   
  46.      .parse(to));   
  47.   }   
  48.   
  49.   // 设置抄送人   
  50.   if (cc != null) {   
  51.    mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress   
  52.      .parse(cc));   
  53.   }   
  54.   
  55.   // 设置暗送人   
  56.   if (bcc != null) {   
  57.    mimeMsg.setRecipients(Message.RecipientType.BCC, InternetAddress   
  58.      .parse(bcc));   
  59.   }   
  60.   // 设置邮件主题   
  61.   mimeMsg.setSubject(subject);   
  62.   // 设置邮件内容,将邮件body部分转化为HTML格式   
  63.   mimeMsg.setContent(body, "text/html ;charset=gbk");   
  64.   
  65.   // 发送邮件   
  66.   Transport transport = mailSession.getTransport();   
  67.   transport.connect(smtp, port, user, password);   
  68.   transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());   
  69.   transport.close();   
  70.  }   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多