码迷,mamicode.com
首页 > 编程语言 > 详细

java 邮件(2)

时间:2016-09-27 10:18:25      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

/**
  * 方法描述:发送带附件的邮件
  *
  * @throws UnsupportedEncodingException
  */
  public static boolean sendEmailWithAttachment(Email email)
      throws UnsupportedEncodingException {
    Properties prop = new Properties();
    prop.put("mail.smtp.host", mailServer);
    prop.put("mail.smtp.auth", "true");
    Authenticator auth = new MailAuthenticator();
    Session session = Session.getDefaultInstance(prop, auth);
    Message message = new MimeMessage(session);
    boolean flag = false;
    try {
      message.setSubject(email.getEmail_subject());// 设置邮件主题
      message.setHeader("Header:", email.getEmail_header()); // 设置邮件标题
      message.setSentDate(new Date()); // 设置发送时间
      Address addressFrom = new InternetAddress(mailAddress, mailAccount); // 设置发信人地址
      message.setFrom(addressFrom);
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(email.getEmail_content(),  "text/html;charset=utf-8");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      MimeBodyPart mimeBodyPart;
      //多个附件
      for (int i = 0; i < email.getEmail_file().size(); i++) {
        Map<String, String> map = email.getEmail_file().get(i);
        String fileSource="";
        String fileName="";
        for (String key : map.keySet()) {
          fileSource = key;
          fileName = map.get(key);
          }
        mimeBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileSource);
        mimeBodyPart.setDataHandler(new DataHandler(source));
        mimeBodyPart.setFileName(MimeUtility.encodeText(fileName));
        multipart.addBodyPart(mimeBodyPart);// Put parts in
      }
      message.setContent(multipart);
     
      // 设置多个收件人地址
      List<String> list = email.getEmail_to();
      String toAddress = SendEmail.getAddress(list);
     
      InternetAddress[] internetAddressTo = new InternetAddress().parse(toAddress);
      message.setRecipients(Message.RecipientType.TO, internetAddressTo);

      // 设置多个抄送地址
      String ccAddress = SendEmail.getAddress(email.getEmail_cc());
      InternetAddress[] internetAddressCC = new InternetAddress().parse(ccAddress);
      message.setRecipients(Message.RecipientType.CC, internetAddressCC);
     
      message.saveChanges();
      System.out.println("开始发送邮件……");

      Transport.send(message);
      System.out.println("发送成功!");
      flag = true;
    } catch (MessagingException e) {
      System.out.println("发送失败!");
      flag = false;
      e.printStackTrace();

    }
    return flag;
  }

java 邮件(2)

标签:

原文地址:http://www.cnblogs.com/northeastTycoon/p/5911736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!