Java Code Examples for javax.mail.internet.MimeBodyPart#setText()

The following examples show how to use javax.mail.internet.MimeBodyPart#setText() . 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: MailCatcherClient.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
private void sendEmail(final Session session, final String from, final String to, final String subject,
                       final String body, final ContentType contentType) {
    try {
        final Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setSentDate(new Date());

        final MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(body, "utf-8", contentType.name().toLowerCase());

        final Multipart multiPart = new MimeMultipart();
        multiPart.addBodyPart(mimeBodyPart);
        message.setContent(multiPart);
        Transport.send(message);
    } catch (final Exception e) {
        LOGGER.severe(e.getMessage());
    }
}
 
Example 2
Source File: MailTestUtil.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
public static MimeMessage createMimeMessageWithAttachment(Session session, File attachment) throws MessagingException, AddressException, IOException {
  MimeMessage message = createMimeMessage(session);

  Multipart multiPart = new MimeMultipart();

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

  MimeBodyPart filePart = new MimeBodyPart();
  filePart.attachFile(attachment);
  multiPart.addBodyPart(filePart);

  message.setContent(multiPart);

  return message;
}
 
Example 3
Source File: SieveFailureMessageComposer.java    From james-project with Apache License 2.0 6 votes vote down vote up
public static MimeMessage composeMessage(Mail aMail, Exception ex, String user) throws MessagingException {
    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText("An error was encountered while processing this mail with the active sieve script for user \""
        + user + "\". The error encountered was:\r\n" + ex.getLocalizedMessage() + "\r\n");
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if (Strings.isNullOrEmpty(originalMessage.getSubject())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();
    return message;
}
 
Example 4
Source File: DSNBounce.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MimeBodyPart createTextMsg(Mail originalMail) throws MessagingException {
    StringBuilder builder = new StringBuilder();

    builder.append(bounceMessage()).append(LINE_BREAK);
    builder.append("Failed recipient(s):").append(LINE_BREAK);
    builder.append(originalMail.getRecipients()
            .stream()
            .map(MailAddress::asString)
            .collect(Collectors.joining(", ")));
    builder.append(LINE_BREAK).append(LINE_BREAK);
    builder.append("Error message:").append(LINE_BREAK);
    builder.append(AttributeUtils.getValueAndCastFromMail(originalMail, DELIVERY_ERROR, String.class).orElse("")).append(LINE_BREAK);
    builder.append(LINE_BREAK);

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText(builder.toString());
    return bodyPart;
}
 
Example 5
Source File: MailTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Message createMimeMessage( String specialCharacters, File attachedFile ) throws Exception {
  Session session = Session.getInstance( new Properties() );
  Message message = new MimeMessage( session );

  MimeMultipart multipart = new MimeMultipart();
  MimeBodyPart attachedFileAndContent = new MimeBodyPart();
  attachedFile.deleteOnExit();
  // create a data source
  URLDataSource fds = new URLDataSource( attachedFile.toURI().toURL() );
  // get a data Handler to manipulate this file type;
  attachedFileAndContent.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  String tempFileName = attachedFile.getName();
  message.setSubject( specialCharacters );
  attachedFileAndContent.setFileName( tempFileName );
  attachedFileAndContent.setText( specialCharacters );

  multipart.addBodyPart( attachedFileAndContent );
  message.setContent( multipart );

  return message;
}
 
Example 6
Source File: ContentModelMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private MimeBodyPart getTextBodyPart(String bodyText, String subtype, String mimeType) throws MessagingException
{
    MimeBodyPart result = new MimeBodyPart();
    result.setText(bodyText, AlfrescoImapConst.UTF_8, subtype);
    result.addHeader(AlfrescoImapConst.CONTENT_TYPE, mimeType + AlfrescoImapConst.CHARSET_UTF8);
    result.addHeader(AlfrescoImapConst.CONTENT_TRANSFER_ENCODING, AlfrescoImapConst.BASE_64_ENCODING);
    return result;
}
 
Example 7
Source File: TestServlet.java    From javamail with Apache License 2.0 5 votes vote down vote up
/**
 * Sand example email
 */
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse response) throws ServletException, IOException {
    String toEmail = httpServletRequest.getParameter("to");
    String body = httpServletRequest.getParameter("body");
    if (toEmail == null || toEmail.length() == 0) {
        throw new ServletException("No \"to\" parameter!");
    }
    if (body == null || body.length() == 0) {
        body = "No body!";
    }
    try {
        Date now = new Date();
        String from = mailSession.getProperty("mail.from");
        if (from == null || from.length() == 0) {
            from = "[email protected]";
        }
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(toEmail) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject("JavaMail test at " + now);
        message.setSentDate(now);
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("Body's text (text)\n\n" + body, "UTF-8");
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<p>Body's text <strong>(html)</strong></p><p>" + body.replace("\n", "<br/>")+"</p>", "text/html; charset=UTF-8");
        Multipart multiPart = new MimeMultipart("alternative");
        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);
        message.setContent(multiPart);
        mailSession.getTransport().sendMessage(message, address);
        httpServletRequest.setAttribute("sent", Boolean.TRUE);
    } catch (Exception ex) {
        httpServletRequest.setAttribute("sent", Boolean.FALSE);
        throw new ServletException("Error sending example e-mail!", ex);
    }
    doGet(httpServletRequest, response);
}
 
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: DatasetNotificationManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendMail(String[] emailAddresses, String subject, String emailContent) throws Exception{

		SessionFacade facade = MailSessionBuilder.newInstance()
			.usingUserProfile()
			.withTimeout(5000)
			.withConnectionTimeout(5000)
			.build();

		// create a message
		Message msg = facade.createNewMimeMessage();

		InternetAddress[] addressTo = new InternetAddress[emailAddresses.length];
		for (int i = 0; i < emailAddresses.length; i++)  {
			addressTo[i] = new InternetAddress(emailAddresses[i]);
		}
		msg.setRecipients(Message.RecipientType.BCC, addressTo);

		// Setting the Subject and Content Type
		msg.setSubject(subject);
		// create and fill the first message part
		MimeBodyPart mbp1 = new MimeBodyPart();
		mbp1.setText(emailContent);
		// create the Multipart and add its parts to it
		Multipart mp = new MimeMultipart();
		mp.addBodyPart(mbp1);
		// add the Multipart to the message
		msg.setContent(mp);

		// send message
		facade.sendMessage(msg);
	}
 
Example 10
Source File: ICSSanitizer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private BodyPart sanitize(BodyPart bodyPart) throws MessagingException {
    if (needsSanitizing(bodyPart)) {
        if (bodyPart instanceof MimeBodyPart) {
            MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
            mimeBodyPart.setText(
                computeBodyFromOriginalCalendar(bodyPart),
                StandardCharsets.UTF_8.name(),
                bodyPart.getContentType().substring(TEXT_PREFIX_SIZE));
            setFileNameIfNeeded(mimeBodyPart);
        }
    }
    return bodyPart;
}
 
Example 11
Source File: Postman.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * Listen for e-mail requests through CDI events and send the message
 *
 * @param mailMessage the message to send
 * @throws Exception if any problem occur in the process
 */
public void send(@Observes MailMessage mailMessage) throws Exception {

    // create the message
    final MimeMessage message = new MimeMessage(this.mailSession);

    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());

    message.setSentDate(new Date());

    final MimeMultipart multipart = new MimeMultipart();

    // message text
    final MimeBodyPart messagePart = new MimeBodyPart();

    messagePart.setText(mailMessage.getContent(), "UTF-8", "html");
    multipart.addBodyPart(messagePart);

    // attachments part
    mailMessage.getAttachments().forEach(file -> {
        try {
            final FileDataSource dataSource = new FileDataSource(file);
            final MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(dataSource));
            attachmentPart.setFileName(dataSource.getName());
            multipart.addBodyPart(attachmentPart);
        } catch (MessagingException ex) {
            throw new BusinessLogicException("error.email.cant-attach-file", ex, file.getName());
        }
    });

    message.setContent(multipart);

    // send
    Transport.send(message);
}
 
Example 12
Source File: AttachmentMailerImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Construct and a send mime email message from an Attachment Mail Message.
 *
 * @param message the Attachement Mail Message
 * @throws MessagingException
 */
@Override
public void sendEmail(AttachmentMailMessage message) throws MessagingException {
    // Construct a mime message from the Attachment Mail Message

    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(message.getMessage());

    MimeBodyPart attachment = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);
    ByteArrayDataSource ds = new ByteArrayDataSource(message.getContent(), message.getType());
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName(message.getFileName());
    multipart.addBodyPart(attachment);
    mimeMessage.setContent(multipart);

    MimeMailMessage mmm = new MimeMailMessage(mimeMessage);

    mmm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
    mmm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
    mmm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
    mmm.setSubject(message.getSubject());
    mmm.setFrom(message.getFromAddress());

    try {
        if ( LOG.isDebugEnabled() ) {
            LOG.debug( "sendEmail() - Sending message: " + mmm.toString() );
        }
        mailSender.send(mmm.getMimeMessage());
    }
    catch (Exception e) {
        LOG.error("sendEmail() - Error sending email.", e);
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: MessageAlteringUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart getAttachmentPart(MimeMessage originalMessage, String head) throws MessagingException, Exception {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    switch (mailet.getInitParameters().getAttachmentType()) {
        case HEADS:
            attachmentPart.setText(head);
            break;
        case BODY:
            try {
                attachmentPart.setText(getMessageBody(originalMessage));
            } catch (Exception e) {
                attachmentPart.setText("body unavailable");
            }
            break;
        case ALL:
            attachmentPart.setText(head + "\r\nMessage:\r\n" + getMessageBody(originalMessage));
            break;
        case MESSAGE:
            attachmentPart.setContent(originalMessage, "message/rfc822");
            break;
        case NONE:
            break;
        case UNALTERED:
            break;
    }
    attachmentPart.setFileName(getFileName(originalMessage.getSubject()));
    attachmentPart.setDisposition(javax.mail.Part.ATTACHMENT);
    return attachmentPart;
}
 
Example 14
Source File: FullExample.java    From DKIM-for-JavaMail with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {

		// read test configuration from test.properties in your classpath
		Properties testProps = TestUtil.readProperties();

		// get a JavaMail Session object 
		Session session = Session.getDefaultInstance(testProps, null);

		
		
		///////// beginning of DKIM FOR JAVAMAIL stuff
		
		// get DKIMSigner object
		DKIMSigner dkimSigner = new DKIMSigner(
				testProps.getProperty("mail.smtp.dkim.signingdomain"),
				testProps.getProperty("mail.smtp.dkim.selector"),
				testProps.getProperty("mail.smtp.dkim.privatekey"));

		/* set an address or user-id of the user on behalf this message was signed;
		 * this identity is up to you, except the domain part must be the signing domain
		 * or a subdomain of the signing domain.
		 */ 
		dkimSigner.setIdentity("fullexample@"+testProps.getProperty("mail.smtp.dkim.signingdomain"));
		
		// get default
		System.out.println("Default headers getting signed if available:");
		TestUtil.printArray(dkimSigner.getDefaultHeadersToSign());

		// the following header will be signed as well if available
		dkimSigner.addHeaderToSign("ASpecialHeader");
		
		// the following header won't be signed
		dkimSigner.removeHeaderToSign("Content-Type");

		// change default canonicalizations
		dkimSigner.setHeaderCanonicalization(Canonicalization.SIMPLE);
		dkimSigner.setBodyCanonicalization(Canonicalization.RELAXED);

		// add length param to the signature, see RFC 4871
		dkimSigner.setLengthParam(true);
		
		// change default signing algorithm
		dkimSigner.setSigningAlgorithm(SigningAlgorithm.SHA1withRSA);

		// add a list of header=value pairs to the signature for debugging reasons 
		dkimSigner.setZParam(true);

		///////// end of DKIM FOR JAVAMAIL stuff
		
		
		

		// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
		Message msg = new SMTPDKIMMessage(session, dkimSigner);
		Multipart mp = new MimeMultipart();
		msg.setFrom(new InternetAddress(testProps.getProperty("mail.smtp.from")));
		if (testProps.getProperty("mail.smtp.to") != null) {
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(testProps.getProperty("mail.smtp.to"), false));
		}
		if (testProps.getProperty("mail.smtp.cc") != null) {
			msg.setRecipients(Message.RecipientType.CC,
					InternetAddress.parse(testProps.getProperty("mail.smtp.cc"), false));
		}

		msg.setSubject("DKIM for JavaMail: FullExample Testmessage");
		
		MimeBodyPart mbp_msgtext = new MimeBodyPart();
        mbp_msgtext.setText(TestUtil.bodyText);
        mp.addBodyPart(mbp_msgtext);
        
        TestUtil.addFileAttachment(mp, testProps.get("mail.smtp.attachment"));
        
        msg.setContent(mp);

        // send the message by JavaMail
		Transport transport = session.getTransport("smtp"); // or smtps ( = TLS)
		transport.connect(testProps.getProperty("mail.smtp.host"),
				testProps.getProperty("mail.smtp.auth.user"),
				testProps.getProperty("mail.smtp.auth.password"));
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();
	}
 
Example 15
Source File: MimeMultipartBuilder.java    From blackduck-alert with Apache License 2.0 4 votes vote down vote up
private MimeBodyPart buildTextBodyPart() throws MessagingException {
    final MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(text, "utf-8");
    return textPart;
}
 
Example 16
Source File: MailSender.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public void sendMail(EmailBean emailBean) throws SendMailException {
  File tempDir = null;
  try {
    MimeMessage message = new MimeMessage(mailSessionProvider.get());
    Multipart contentPart = new MimeMultipart();

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
    contentPart.addBodyPart(bodyPart);

    if (emailBean.getAttachments() != null) {
      tempDir = Files.createTempDir();
      for (Attachment attachment : emailBean.getAttachments()) {
        // Create attachment file in temporary directory
        byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
        File attachmentFile = new File(tempDir, attachment.getFileName());
        Files.write(attachmentContent, attachmentFile);

        // Attach the attachment file to email
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.attachFile(attachmentFile);
        attachmentPart.setContentID("<" + attachment.getContentId() + ">");
        contentPart.addBodyPart(attachmentPart);
      }
    }

    message.setContent(contentPart);
    message.setSubject(emailBean.getSubject(), "UTF-8");
    message.setFrom(new InternetAddress(emailBean.getFrom(), true));
    message.setSentDate(new Date());
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

    if (emailBean.getReplyTo() != null) {
      message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
    }
    LOG.info(
        "Sending from {} to {} with subject {}",
        emailBean.getFrom(),
        emailBean.getTo(),
        emailBean.getSubject());

    Transport.send(message);
    LOG.debug("Mail sent");
  } catch (Exception e) {
    LOG.error(e.getLocalizedMessage());
    throw new SendMailException(e.getLocalizedMessage(), e);
  } finally {
    if (tempDir != null) {
      try {
        FileUtils.deleteDirectory(tempDir);
      } catch (IOException exception) {
        LOG.error(exception.getMessage());
      }
    }
  }
}
 
Example 17
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Sets the content for a message. Also attaches files to the message.
 * @throws MessagingException
 */
protected void setContent(String content, List<Attachment> attachments, MimeMessage msg,
		String contentType, String charset, String multipartSubtype) throws AttachmentSizeException, MessagingException {

	ArrayList<MimeBodyPart> embeddedAttachments = new ArrayList<MimeBodyPart>();
	if (attachments != null && attachments.size() > 0) {
		int maxAttachmentSize = serverConfigurationService.getInt(MAIL_SENDFROMSAKAI_MAXSIZE, DEFAULT_MAXSIZE);
		long attachmentRunningTotal = 0L;

		// Add attachments to messages
		for (Attachment attachment : attachments) {
			// attach the file to the message
			MimeBodyPart mbp = createAttachmentPart(attachment);
			long mbpSize = (long) mbp.getSize();

			if (mbpSize == -1L) {
				// This is normal. See MimeBodyPart documentation.
				mbpSize = attachment.getSizeIfFile().orElse(-1L);
			}

			if (mbpSize == -1L) {
				log.warn("Failed to get size of email attachment. This could result in the limit being exceeded");
			}

			if ( (attachmentRunningTotal + mbpSize) < maxAttachmentSize ) {
				embeddedAttachments.add(mbp);
				attachmentRunningTotal = attachmentRunningTotal + mbpSize;
			} else {
				throw new AttachmentSizeException("Attachments too large", attachmentRunningTotal + mbpSize);
			}
		}
	}

	// if no direct attachments, keep the message simple and add the content as text.
	if (embeddedAttachments.size() == 0) {
		// if no contentType specified, go with text/plain
		if (contentType == null) {
			msg.setText(content, charset);
		} else {
			msg.setContent(content, contentType);
		}
	} else {
		// the multipart was constructed (ie. attachments available), use it as the message content
		// create a multipart container
		Multipart multipart = (multipartSubtype != null) ? new MimeMultipart(multipartSubtype) : new MimeMultipart();

		// create a body part for the message text
		MimeBodyPart msgBodyPart = new MimeBodyPart();
		if (contentType == null) {
			msgBodyPart.setText(content, charset);
		} else {
			msgBodyPart.setContent(content, contentType);
		}

		// add the message part to the container
		multipart.addBodyPart(msgBodyPart);

		// add attachments
		for (MimeBodyPart attachPart : embeddedAttachments) {
			multipart.addBodyPart(attachPart);
		}

		// set the multipart container as the content of the message
		msg.setContent(multipart);
	}
}
 
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: EmailLogServlet.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public boolean sendLog(String host, String userId, String password,
        String to, String from, String subject, String message,
        File filename) {
    boolean success = true;
    System.out.println("host: " + host);
    System.out.println("userId: " + userId);
    // Fortify Mod: commented out clear text password.
    // System.out.println("password: " + password);
    System.out.println("to: " + to);
    System.out.println("from: " + from);
    System.out.println("subject: " + subject);
    System.out.println("message: " + message);
    System.out.println("filename: " + filename.getName());
    System.out.println("filename: " + filename.getAbsolutePath());

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");

    Session session = Session.getInstance(props, null);
    session.setDebug(true);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(message);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.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);

        // set the Date: header
        msg.setSentDate(new Date());

        // connect to the transport
        Transport trans = session.getTransport("smtp");
        trans.connect(host, userId, password);

        // send the message
        trans.sendMessage(msg, msg.getAllRecipients());

        // smtphost
        trans.close();

    } catch (MessagingException mex) {
        success = false;
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
    return success;
}
 
Example 20
Source File: MessageAlteringUtils.java    From james-project with Apache License 2.0 4 votes vote down vote up
private BodyPart getBodyPart(Mail originalMail, MimeMessage originalMessage, String head) throws MessagingException, Exception {
    MimeBodyPart part = new MimeBodyPart();
    part.setText(getText(originalMail, originalMessage, head));
    part.setDisposition(javax.mail.Part.INLINE);
    return part;
}