Java Code Examples for javax.mail.Multipart#addBodyPart()

The following examples show how to use javax.mail.Multipart#addBodyPart() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GMailClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: MailTestUtil.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: MailUtil.java    From sdudoc with MIT License 5 votes vote down vote up
/** 发送用户验证的邮件 */
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();
	}
}
 
Example 4
Source File: MailUtil.java    From sdudoc with MIT License 5 votes vote down vote up
/** 发送密码重置的邮件 */
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();
	}
}
 
Example 5
Source File: TestSendIcalMessage.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 6
Source File: MailingListPublisher.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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());
}
 
Example 7
Source File: MailHandler.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: DefaultMailService.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@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 );
}
 
Example 9
Source File: TestMailClient.java    From holdmail with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: ForgotPasswordCommand.java    From FlexibleLogin with MIT License 5 votes vote down vote up
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;
}
 
Example 11
Source File: EmailNotifier.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: JavaMailSender.java    From ogham with Apache License 2.0 4 votes vote down vote up
private static void moveBodyToRelatedContainer(Multipart root, Multipart related) throws MessagingException {
	while (root.getCount() > 0) {
		related.addBodyPart(root.getBodyPart(0));
		root.removeBodyPart(0);
	}
}
 
Example 13
Source File: BigAttachmentTest.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
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();
}
 
Example 14
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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);
   }
}
 
Example 15
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
    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);
   }
 }
 
Example 16
Source File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * 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);
	}

}
 
Example 17
Source File: EmailUtil.java    From Insights with Apache License 2.0 4 votes vote down vote up
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;
	} 

}
 
Example 18
Source File: SendEMail.java    From tn5250j with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: MailDocumentDispatchChannel.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@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;
}
 
Example 20
Source File: JavaMailSender.java    From ogham with Apache License 2.0 4 votes vote down vote up
private static void addRelatedContainer(Multipart root, Multipart related) throws MessagingException {
	MimeBodyPart part = new MimeBodyPart();
	part.setContent(related);
	root.addBodyPart(part);
}