javax.mail.Multipart#addBodyPart ( )源码实例Demo

下面列出了javax.mail.Multipart#addBodyPart ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: blynk-server   文件: GMailClient.java
@Override
public void sendHtmlWithAttachment(String to, String subj, String body,
                                   QrHolder[] attachmentData) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");

    Multipart multipart = new MimeMultipart();

    MimeBodyPart bodyMessagePart = new MimeBodyPart();
    bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);

    multipart.addBodyPart(bodyMessagePart);

    attachQRs(multipart, attachmentData);
    attachCSV(multipart, attachmentData);

    message.setContent(multipart);

    Transport.send(message);

    log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}
 
源代码2 项目: camunda-bpm-mail   文件: MailTestUtil.java
public static MimeMessage createMimeMessageWithHtml(Session session) throws MessagingException, AddressException {
  MimeMessage message = createMimeMessage(session);

  Multipart multiPart = new MimeMultipart();

  MimeBodyPart textPart = new MimeBodyPart();
  textPart.setText("text");
  multiPart.addBodyPart(textPart);

  MimeBodyPart htmlPart = new MimeBodyPart();
  htmlPart.setContent("<b>html</b>", MailContentType.TEXT_HTML.getType());
  multiPart.addBodyPart(htmlPart);

  message.setContent(multiPart);
  return message;
}
 
源代码3 项目: sdudoc   文件: MailUtil.java
/** 发送用户验证的邮件 */
public static void sendAccountActiveEmail(User user) {

	String subject = "sdudoc邮箱验证提醒";
	String content = "感谢您于" + DocUtil.getDateTime() + "在sdudoc注册,复制以下链接,即可完成安全验证:"
			+ "http://127.0.0.1:8080/sdudoc/activeUser.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请过验证邮箱 ,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		// 设定发送邮件的地址
		message.setFrom(new InternetAddress(from));
		// 设定接受邮件的地址
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		// 设定邮件主题
		message.setSubject(subject);
		// 设定邮件内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf8");// 给BodyPart对象设置内容和格式/编码方式
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		// message.setText(content);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
源代码4 项目: sdudoc   文件: MailUtil.java
/** 发送密码重置的邮件 */
public static void sendResetPasswordEmail(User user) {
	String subject = "sdudoc密码重置提醒";
	String content = "您于" + DocUtil.getDateTime() + "在sdudoc找回密码,点击以下链接,进行密码重置:"
			+ "http://127.0.0.1:8080/sdudoc/resetPasswordCheck.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请密码重置,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		message.setSubject(subject);
		BodyPart mdp = new MimeBodyPart();
		mdp.setContent(content, "text/html;charset=utf8");
		Multipart mm = new MimeMultipart();
		mm.addBodyPart(mdp);
		message.setContent(mm);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
源代码5 项目: contribution   文件: MailingListPublisher.java
/**
 * Publish post.
 *
 * @throws MessagingException if an error occurs while publishing.
 * @throws IOException if there are problems with reading file with the post text.
 */
public void publish() throws MessagingException, IOException {
    final Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", SMTP_HOST);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.auth", true);

    final Session session = Session.getInstance(props, null);
    final MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.addRecipients(Message.RecipientType.TO,
            InternetAddress.parse(RECIPIENT_ADDRESS));

    final String post = new String(Files.readAllBytes(Paths.get(postFilename)),
            StandardCharsets.UTF_8);

    final BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(post, "text/plain");

    final Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);

    final Transport transport = session.getTransport("smtp");
    transport.connect(SMTP_HOST, username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
 
源代码6 项目: holdmail   文件: TestMailClient.java
private void createMultiMimePart(Message message, String textBody, String htmlBody) throws MessagingException {
    Multipart mp = new MimeMultipart();

    if (StringUtils.isNotBlank(textBody)) {
        mp.addBodyPart(createTextBodyPart(textBody));
    }
    if (StringUtils.isNotBlank(htmlBody)) {
        mp.addBodyPart(createHtmlBodyPart(htmlBody));
    }

    message.setContent(mp);
}
 
源代码7 项目: FlexibleLogin   文件: ForgotPasswordCommand.java
private MimeMessage buildMessage(User player, String email, String newPassword, MailConfig emailConfig,
                                 Session session) throws MessagingException, UnsupportedEncodingException {
    String serverName = Sponge.getServer().getBoundAddress()
            .map(sa -> sa.getAddress().getHostAddress())
            .orElse("Minecraft Server");
    ImmutableMap<String, String> variables = ImmutableMap.of("player", player.getName(),
            "server", serverName,
            "password", newPassword);

    MimeMessage message = new MimeMessage(session);
    String senderEmail = emailConfig.getAccount();

    //sender email with an alias
    message.setFrom(new InternetAddress(senderEmail, emailConfig.getSenderName()));
    message.setRecipient(RecipientType.TO, new InternetAddress(email, player.getName()));
    message.setSubject(emailConfig.getSubject(serverName, player.getName()).toPlain());

    //current time
    message.setSentDate(Calendar.getInstance().getTime());
    String textContent = emailConfig.getText(serverName, player.getName(), newPassword).toPlain();

    //html part
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(textContent, "text/html; charset=UTF-8");

    //plain text
    BodyPart textPart = new MimeBodyPart();
    textPart.setContent(textContent.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " "), "text/plain; charset=UTF-8");

    Multipart alternative = new MimeMultipart("alternative");
    alternative.addBodyPart(htmlPart);
    alternative.addBodyPart(textPart);
    message.setContent(alternative);
    return message;
}
 
源代码8 项目: streamline   文件: EmailNotifier.java
/**
 * Construct a {@link Message} from the map of message field values
 */
private Message getEmailMessage(Map<String, String> fields) throws MessagingException {
    Message msg = new MimeMessage(emailSession);
    msg.setFrom(new InternetAddress(fields.get(FIELD_FROM.key)));
    InternetAddress[] address = {new InternetAddress(fields.get(FIELD_TO.key))};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(fields.get(FIELD_SUBJECT.key));
    msg.setSentDate(new Date());
    Multipart content = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(fields.get(FIELD_BODY.key), fields.get(FIELD_CONTENT_TYPE.key));
    content.addBodyPart(mimeBodyPart);
    msg.setContent(content);
    return msg;
}
 
源代码9 项目: packagedrone   文件: DefaultMailService.java
@Override
public void sendMessage ( final String to, final String subject, final String text, final String html ) throws Exception
{
    // create message

    final Message message = createMessage ( to, subject );

    if ( html != null && !html.isEmpty () )
    {
        // create multipart

        final Multipart parts = new MimeMultipart ( "alternative" );

        // set text

        final MimeBodyPart textPart = new MimeBodyPart ();
        textPart.setText ( text, "UTF-8" );
        parts.addBodyPart ( textPart );

        // set HTML, optionally

        final MimeBodyPart htmlPart = new MimeBodyPart ();
        htmlPart.setContent ( html, "text/html; charset=utf-8" );
        parts.addBodyPart ( htmlPart );

        // set parts

        message.setContent ( parts );
    }
    else
    {
        // plain text
        message.setText ( text );
    }

    // send message

    sendMessage ( message );
}
 
源代码10 项目: openmeetings   文件: MailHandler.java
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception {
	log.debug("setMessageBody for iCal message");
	// -- Create a new message --
	Multipart multipart = new MimeMultipart();

	Multipart multiBody = new MimeMultipart("alternative");
	BodyPart html = new MimeBodyPart();
	html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8")));
	multiBody.addBodyPart(html);

	BodyPart iCalContent = new MimeBodyPart();
	iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage");
	iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"text/calendar; charset=UTF-8; method=REQUEST")));
	multiBody.addBodyPart(iCalContent);
	BodyPart body = new MimeBodyPart();
	body.setContent(multiBody);
	multipart.addBodyPart(body);

	BodyPart iCalAttachment = new MimeBodyPart();
	iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"application/ics")));
	iCalAttachment.removeHeader("Content-Transfer-Encoding");
	iCalAttachment.addHeader("Content-Transfer-Encoding", "base64");
	iCalAttachment.removeHeader("Content-Type");
	iCalAttachment.addHeader("Content-Type", "application/ics");
	iCalAttachment.setFileName("invite.ics");
	multipart.addBodyPart(iCalAttachment);

	msg.setContent(multipart);
	return msg;
}
 
源代码11 项目: openmeetings   文件: TestSendIcalMessage.java
private void sendIcalMessage() throws Exception {
	log.debug("sendIcalMessage");

	// Building MimeMessage
	MimeMessage mimeMessage = mailHandler.getBasicMimeMessage();
	mimeMessage.setSubject(subject);
	mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false));

	// -- Create a new message --
	BodyPart msg = new MimeBodyPart();
	msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody,
			"text/html; charset=\"utf-8\"")));

	Multipart multipart = new MimeMultipart();

	BodyPart iCalAttachment = new MimeBodyPart();
	iCalAttachment.setDataHandler(new DataHandler(
			new javax.mail.util.ByteArrayDataSource(
					new ByteArrayInputStream(iCalMimeBody),
					"text/calendar;method=REQUEST;charset=\"UTF-8\"")));
	iCalAttachment.setFileName("invite.ics");

	multipart.addBodyPart(iCalAttachment);
	multipart.addBodyPart(msg);

	mimeMessage.setSentDate(new Date());
	mimeMessage.setContent(multipart);

	// -- Set some other header information --
	// mimeMessage.setHeader("X-Mailer", "XML-Mail");
	// mimeMessage.setSentDate(new Date());

	// Transport trans = session.getTransport("smtp");
	Transport.send(mimeMessage);
}
 
源代码12 项目: Open-Lowcode   文件: MailDaemon.java
/**
 * sends invitation
 * 
 * @param session     session connection to the SMTP server
 * @param toemails    list of recipient e-mails
 * @param subject     invitation subject
 * @param body        invitation start
 * @param fromemail   user sending the invitation
 * @param startdate   start date of the invitation
 * @param enddate     end date of the invitation
 * @param location    location of the invitation
 * @param uid         unique id
 * @param cancelation true if this is a cancelation
 */
private void sendInvitation(Session session, String[] toemails, String subject, String body, String fromemail,
		Date startdate, Date enddate, String location, String uid, boolean cancelation) {
	try {
		// prepare mail mime message
		MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
		mimetypes.addMimeTypes("text/calendar ics ICS");
		// register the handling of text/calendar mime type
		MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
		mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");

		MimeMessage msg = new MimeMessage(session);
		// set message headers

		msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
		msg.addHeader("format", "flowed");
		msg.addHeader("Content-Transfer-Encoding", "8bit");
		InternetAddress fromemailaddress = new InternetAddress(fromemail);
		msg.setFrom(fromemailaddress);
		msg.setReplyTo(InternetAddress.parse(fromemail, false));
		msg.setSubject(subject, "UTF-8");
		msg.setSentDate(new Date());

		// set recipient

		InternetAddress[] recipients = new InternetAddress[toemails.length + 1];

		String attendeesinvcalendar = "";
		for (int i = 0; i < toemails.length; i++) {
			recipients[i] = new InternetAddress(toemails[i]);
			attendeesinvcalendar += "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
					+ toemails[i] + "\n";
		}

		recipients[toemails.length] = fromemailaddress;
		msg.setRecipients(Message.RecipientType.TO, recipients);

		Multipart multipart = new MimeMultipart("alternative");
		// set body
		MimeBodyPart descriptionPart = new MimeBodyPart();
		descriptionPart.setContent(body, "text/html; charset=utf-8");
		multipart.addBodyPart(descriptionPart);

		// set invitation
		BodyPart calendarPart = new MimeBodyPart();

		String method = "METHOD:REQUEST\n";
		if (cancelation)
			method = "METHOD:CANCEL\n";

		String calendarContent = "BEGIN:VCALENDAR\n" + method + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n"
				+ "BEGIN:VEVENT\n" + "DTSTAMP:" + iCalendarDateFormat.format(new Date()) + "\n" + "DTSTART:"
				+ iCalendarDateFormat.format(startdate) + "\n" + "DTEND:" + iCalendarDateFormat.format(enddate)
				+ "\n" + "SUMMARY:" + subject + "\n" + "UID:" + uid + "\n" + attendeesinvcalendar
				+ "ORGANIZER:MAILTO:" + fromemail + "\n" + "LOCATION:" + location + "\n" + "DESCRIPTION:" + subject
				+ "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n"
				+ "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n"
				+ "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR";

		calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
		calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
		multipart.addBodyPart(calendarPart);
		msg.setContent(multipart);
		logger.severe("Invitation is ready");
		Transport.send(msg);

		logger.severe("EMail Invitation Sent Successfully!! to " + attendeesinvcalendar);
	} catch (Exception e) {
		logger.severe(
				"--- Exception in sending invitation --- " + e.getClass().toString() + " - " + e.getMessage());
		if (e.getCause() != null)
			logger.severe(" cause  " + e.getCause().getClass().toString() + " - " + e.getCause().getMessage());
		throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:"
				+ this.smtpserver + " - port:" + this.port + " - user:" + this.user);
	}

}
 
源代码13 项目: ogham   文件: JavaMailSender.java
private static void addRelatedContainer(Multipart root, Multipart related) throws MessagingException {
	MimeBodyPart part = new MimeBodyPart();
	part.setContent(related);
	root.addBodyPart(part);
}
 
@Override
public boolean dispatch(BIObject document, byte[] executionOutput) {
	Map parametersMap;
	String contentType;
	String fileExtension;
	IDataStore emailDispatchDataStore;
	String nameSuffix;
	String descriptionSuffix;
	String containedFileName;
	String zipFileName;
	boolean reportNameInSubject;

	logger.debug("IN");
	try {
		parametersMap = dispatchContext.getParametersMap();
		contentType = dispatchContext.getContentType();
		fileExtension = dispatchContext.getFileExtension();
		emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
		nameSuffix = dispatchContext.getNameSuffix();
		descriptionSuffix = dispatchContext.getDescriptionSuffix();
		containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext
				.getContainedFileName() : document.getName();
		zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName()
				: document.getName();
		reportNameInSubject = dispatchContext.isReportNameInSubject();

		SessionFacade facade = MailSessionBuilder.newInstance()
			.usingSchedulerProfile()
			.build();

		String mailSubj = dispatchContext.getMailSubj();
		mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

		String mailTxt = dispatchContext.getMailTxt();

		String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
		if (recipients == null || recipients.length == 0) {
			logger.error("No recipients found for email sending!!!");
			return false;
		}

		// create a message
		Message msg = facade.createNewMimeMessage();
		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);
		// Setting the Subject and Content Type

		String subject = mailSubj;

		if (reportNameInSubject) {
			subject += " " + document.getName() + nameSuffix;
		}

		msg.setSubject(subject);
		// create and fill the first message part
		MimeBodyPart mbp1 = new MimeBodyPart();
		mbp1.setText(mailTxt + "\n" + descriptionSuffix);
		// create the second message part
		MimeBodyPart mbp2 = new MimeBodyPart();
		// attach the file to the message

		SchedulerDataSource sds = null;
		// if zip requested
		if (dispatchContext.isZipMailDocument()) {
			mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
		}
		// else
		else {
			sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension);
			mbp2.setDataHandler(new DataHandler(sds));
			mbp2.setFileName(sds.getName());
		}

		// create the Multipart and add its parts to it
		Multipart mp = new MimeMultipart();
		mp.addBodyPart(mbp1);
		mp.addBodyPart(mbp2);
		// add the Multipart to the message
		msg.setContent(mp);
		// send message
		facade.sendMessage(msg);
		logger.info("Mail sent for document with label " + document.getLabel());

	} catch (Exception e) {
		logger.error("Error while sending schedule result mail", e);
		return false;
	} finally {
		logger.debug("OUT");
	}
	return true;
}
 
源代码15 项目: tn5250j   文件: SendEMail.java
/**
 * This method processes the send request from the compose form
 */
public boolean send() throws Exception {

   try {
      if(!loadConfig(configFile))
         return false;

      Session session = Session.getDefaultInstance(SMTPProperties, null);
      session.setDebug(false);

      // create the Multipart and its parts to it
      Multipart mp = new MimeMultipart();

      Message msg = new MimeMessage(session);
      InternetAddress[] toAddrs = null, ccAddrs = null;

      toAddrs = InternetAddress.parse(to, false);
      msg.setRecipients(Message.RecipientType.TO, toAddrs);

      if (cc != null) {
         ccAddrs = InternetAddress.parse(cc, false);
         msg.setRecipients(Message.RecipientType.CC, ccAddrs);
      }

      if (subject != null)
         msg.setSubject(subject.trim());

      if (from == null)
         from = SMTPProperties.getProperty("mail.smtp.from");

      if (from != null && from.length() > 0) {
      	pers = SMTPProperties.getProperty("mail.smtp.realname");
      	if (pers != null) msg.setFrom(new InternetAddress(from, pers));
      }

      if (message != null && message.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart mbp = new MimeBodyPart();
         mbp.setText(message,"us-ascii");
         mp.addBodyPart(mbp);
      }

      msg.setSentDate(new Date());

      if (attachment != null && attachment.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart abp = new MimeBodyPart();

         abp.setText(attachment,"us-ascii");

         if (attachmentName == null || attachmentName.length() == 0)
            abp.setFileName("tn5250j.txt");
         else
            abp.setFileName(attachmentName);
         mp.addBodyPart(abp);

      }

      if (fileName != null && fileName.length() > 0) {
         // create and fill the attachment message part
         MimeBodyPart fbp = new MimeBodyPart();

         fbp.setText("File sent using tn5250j","us-ascii");

         if (attachmentName == null || attachmentName.length() == 0) {
            	fbp.setFileName("tn5250j.txt");
         }
         else
            fbp.setFileName(attachmentName);

          // Get the attachment
          DataSource source = new FileDataSource(fileName);

          // Set the data handler to the attachment
          fbp.setDataHandler(new DataHandler(source));

         mp.addBodyPart(fbp);

      }

      // add the Multipart to the message
      msg.setContent(mp);

      // send the message
      Transport.send(msg);
      return true;
   }
   catch (SendFailedException sfe) {
      showFailedException(sfe);
   }
   return false;
}
 
源代码16 项目: Insights   文件: EmailUtil.java
public void sendEmail(Mail mail,EmailConfiguration emailConf, String emailBody) throws MessagingException,
																				IOException,UnsupportedEncodingException {

	Properties props = System.getProperties();
	props.put(EmailConstants.SMTPHOST, emailConf.getSmtpHostServer());
	props.put(EmailConstants.SMTPPORT, emailConf.getSmtpPort());
	props.put("mail.smtp.auth", emailConf.getIsAuthRequired());
	props.put("mail.smtp.starttls.enable", emailConf.getSmtpStarttlsEnable());

	// Create a Session object to represent a mail session with the specified
	// properties.
	Session session = Session.getDefaultInstance(props);
	MimeMessage msg = new MimeMessage(session);
	msg.addHeader(EmailConstants.CONTENTTYPE, EmailConstants.CHARSET);
	msg.addHeader(EmailConstants.FORMAT, EmailConstants.FLOWED);
	msg.addHeader(EmailConstants.ENCODING, EmailConstants.BIT);
	msg.setFrom(new InternetAddress(mail.getMailFrom(), EmailConstants.NOREPLY));
	msg.setReplyTo(InternetAddress.parse(mail.getMailTo(), false));
	msg.setSubject(mail.getSubject(), EmailConstants.UTF);
	msg.setSentDate(new Date());
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getMailTo(), false));
	MimeBodyPart contentPart = new MimeBodyPart();
	contentPart.setContent(emailBody, EmailConstants.HTML);

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(contentPart);

	String imageId="logoImage";
	String imagePath="/img/Insights.jpg";
	MimeBodyPart imagePart = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart);

	imageId="footerImage";
	imagePath="/img/FooterImg.jpg";
	MimeBodyPart imagePart_1 = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart_1);

	msg.setContent(multipart);

	try (Transport transport = session.getTransport();) {
		LOG.debug("Sending email...");

		transport.connect(emailConf.getSmtpHostServer(), emailConf.getSmtpUserName(),emailConf.getSmtpPassword());

		// Send the email.
		transport.sendMessage(msg, msg.getAllRecipients());
		LOG.debug("Email sent!");
	} catch (Exception ex) {
		LOG.error("Error sending email",ex);
		throw ex;
	} 

}
 
源代码17 项目: ogham   文件: JavaMailSender.java
private static void moveBodyToRelatedContainer(Multipart root, Multipart related) throws MessagingException {
	while (root.getCount() > 0) {
		related.addBodyPart(root.getBodyPart(0));
		root.removeBodyPart(0);
	}
}
 
源代码18 项目: cacheonix-core   文件: SMTPAppender.java
/**
    Send the contents of the cyclic buffer as an e-mail message.
  */
 protected
 void sendBuffer() {

   // Note: this code already owns the monitor for this
   // appender. This frees us from needing to synchronize on 'cb'.
   try {
     MimeBodyPart part = new MimeBodyPart();

     StringBuffer sbuf = new StringBuffer();
     String t = layout.getHeader();
     if(t != null)
sbuf.append(t);
     int len =  cb.length();
     for(int i = 0; i < len; i++) {
//sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if(layout.ignoresThrowable()) {
  String[] s = event.getThrowableStrRep();
  if (s != null) {
    for(int j = 0; j < s.length; j++) {
      sbuf.append(s[j]);
      sbuf.append(Layout.LINE_SEP);
    }
  }
}
     }
     t = layout.getFooter();
     if(t != null)
sbuf.append(t);
     part.setContent(sbuf.toString(), layout.getContentType());

     Multipart mp = new MimeMultipart();
     mp.addBodyPart(part);
     msg.setContent(mp);

     msg.setSentDate(new Date());
     Transport.send(msg);
   } catch(Exception e) {
     LogLog.error("Error occured while sending e-mail notification.", e);
   }
 }
 
源代码19 项目: cacheonix-core   文件: SMTPAppender.java
/**
 * Send the contents of the cyclic buffer as an e-mail message.
 */
private final void sendBuffer() {

   // Note: this code already owns the monitor for this
   // appender. This frees us from needing to synchronize on 'cb'.
   try {
      final MimeBodyPart part = new MimeBodyPart();

      final StringBuilder sbuf = new StringBuilder(100);
      String t = layout.getHeader();
      if (t != null) {
         sbuf.append(t);
      }
      final int len = cb.length();
      for (int i = 0; i < len; i++) {
         //sbuf.append(MimeUtility.encodeText(layout.format(cb.get())));
         final LoggingEvent event = cb.get();
         sbuf.append(layout.format(event));
         if (layout.ignoresThrowable()) {
            final String[] s = event.getThrowableStrRep();
            if (s != null) {
               for (final String value : s) {
                  sbuf.append(value);
                  sbuf.append(Layout.LINE_SEP);
               }
            }
         }
      }
      t = layout.getFooter();
      if (t != null) {
         sbuf.append(t);
      }
      part.setContent(sbuf.toString(), layout.getContentType());

      final Multipart mp = new MimeMultipart();
      mp.addBodyPart(part);
      msg.setContent(mp);

      msg.setSentDate(new Date());
      Transport.send(msg);
   } catch (final Exception e) {
      LogLog.error("Error occurred while sending e-mail notification.", e);
   }
}
 
源代码20 项目: subethasmtp   文件: BigAttachmentTest.java
/** */
public void testAttachments() throws Exception
{
	if (BIGFILE_PATH.equals(TO_CHANGE))
	{
		log.error("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !");
	}
	assertNotSame("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !", TO_CHANGE, BIGFILE_PATH);
	Properties props = System.getProperties();
	props.setProperty("mail.smtp.host", "localhost");
	props.setProperty("mail.smtp.port", SMTP_PORT+"");
	Session session = Session.getInstance(props);

	MimeMessage baseMsg = new MimeMessage(session);
	MimeBodyPart bp1 = new MimeBodyPart();
	bp1.setHeader("Content-Type", "text/plain");
	bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

	// Attach the file
	MimeBodyPart bp2 = new MimeBodyPart();
	FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
	DataHandler dh = new DataHandler(fileAttachment);
	bp2.setDataHandler(dh);
	bp2.setFileName(fileAttachment.getName());

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(bp1);
	multipart.addBodyPart(bp2);

	baseMsg.setFrom(new InternetAddress("Ted <[email protected]>"));
	baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress(
			"[email protected]"));
	baseMsg.setSubject("Test Big attached file message");
	baseMsg.setContent(multipart);
	baseMsg.saveChanges();

	log.debug("Send started");
	Transport t = new SMTPTransport(session, new URLName("smtp://localhost:"+SMTP_PORT));
	long started = System.currentTimeMillis();
	t.connect();
	t.sendMessage(baseMsg, new Address[] {new InternetAddress(
			"[email protected]")});
	t.close();
	started = System.currentTimeMillis() - started;
	log.info("Elapsed ms = "+started);

	WiserMessage msg = this.server.getMessages().get(0);

	assertEquals(1, this.server.getMessages().size());
	assertEquals("[email protected]", msg.getEnvelopeReceiver());

	File compareFile = File.createTempFile("attached", ".tmp");
	log.debug("Writing received attachment ...");

	FileOutputStream fos = new FileOutputStream(compareFile);
	((MimeMultipart) msg.getMimeMessage().getContent()).getBodyPart(1).getDataHandler().writeTo(fos);
	fos.close();
	log.debug("Checking integrity ...");
	assertTrue(this.checkIntegrity(new File(BIGFILE_PATH), compareFile));
	log.debug("Checking integrity DONE");
	compareFile.delete();
}