Java Code Examples for javax.mail.BodyPart#setDataHandler()

The following examples show how to use javax.mail.BodyPart#setDataHandler() . 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: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Send a calendar message.
 * 
 * @param mail
 *            The mail to send
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occurred during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
    Message msg = prepareMessage( mail, session );
    msg.setHeader( HEADER_NAME, HEADER_VALUE );

    MimeMultipart multipart = new MimeMultipart( );
    BodyPart msgBodyPart = new MimeBodyPart( );
    msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );

    multipart.addBodyPart( msgBodyPart );

    BodyPart calendarBodyPart = new MimeBodyPart( );
    calendarBodyPart.setContent( mail.getCalendarMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
                    + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
                    + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
    calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
    multipart.addBodyPart( calendarBodyPart );

    msg.setContent( multipart );

    sendMessage( msg, transport );
}
 
Example 2
Source File: Mail.java    From mobikul-standalone-pos with MIT License 5 votes vote down vote up
public void addAttachment(String filepath, String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    javax.activation.DataSource source = new FileDataSource(filepath);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    _multipart.addBodyPart(messageBodyPart);
}
 
Example 3
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private static BodyPart getBodyPart(String fileLoc, FilenameFilter fexFilter) throws MessagingException, IOException {
    BodyPart messageBodyPart = new MimeBodyPart();
    File fileName = new File(fileLoc);
    if (fileName.isDirectory()) {
        fileName = zipFolder(fileLoc, fexFilter);
    }
    DataSource source = new FileDataSource(fileName);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(fileName.getName());
    return messageBodyPart;
}
 
Example 4
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 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: JavaMailWrapper.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
       BodyPart attachment = new MimeBodyPart();
       attachment.setDataHandler(data);
       attachment.setFileName(name);
       attachment.setHeader("Content-ID", "<" + name + ">");
       iBody.addBodyPart(attachment);
}
 
Example 7
Source File: GMailSender.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
public void addAttachment(String filename) throws Exception 
{ 
 if(filename!=null)
 {
  BodyPart messageBodyPart = new MimeBodyPart(); 
  DataSource source = new FileDataSource(filename); 
  messageBodyPart.setDataHandler(new DataHandler(source)); 
  messageBodyPart.setFileName(filename); 

  multipart.addBodyPart(messageBodyPart); 
 }

}
 
Example 8
Source File: Mail.java    From AccelerationAlert with Apache License 2.0 5 votes vote down vote up
public void addAttachment(String filename) throws Exception
{
	BodyPart messageBodyPart = new MimeBodyPart();
	DataSource source = new FileDataSource(filename);
	messageBodyPart.setDataHandler(new DataHandler(source));
	messageBodyPart.setFileName(filename);

	_multipart.addBodyPart(messageBodyPart);
}
 
Example 9
Source File: MailSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
private void setAttachments(MailSession mailSession, MimeMessage msg, String messageTypeWithCharset) throws MessagingException {
	List<MailAttachmentStream> attachmentList = mailSession.getAttachmentList();
	String message = mailSession.getMessage();
	if (attachmentList == null || attachmentList.size() == 0) {
		log.debug("no attachments found to attach to mailSession");
		msg.setContent(message, messageTypeWithCharset);
	} else {
		if(log.isDebugEnabled()) log.debug("found ["+attachmentList.size()+"] attachments to attach to mailSession");
		Multipart multipart = new MimeMultipart();
		BodyPart messagePart = new MimeBodyPart();
		messagePart.setContent(message, messageTypeWithCharset);
		multipart.addBodyPart(messagePart);

		int counter = 0;
		for (MailAttachmentStream attachment : attachmentList) {
			counter++;
			String name = attachment.getName();
			if (StringUtils.isEmpty(name)) {
				name = getDefaultAttachmentName() + counter;
			}
			log.debug("found attachment [" + attachment + "]");

			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setFileName(name);

			try {
				ByteArrayDataSource bads = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType());
				bads.setName(attachment.getName());
				messageBodyPart.setDataHandler(new DataHandler(bads));
			} catch (IOException e) {
				log.error("error attaching attachment to MailSession", e);
			}

			multipart.addBodyPart(messageBodyPart);
		}
		msg.setContent(multipart);
	}
}
 
Example 10
Source File: MultiPartEmail.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Attach a file specified as a DataSource interface.
 *
 * @param ds A DataSource interface for the file.
 * @param name The name field for the attachment.
 * @param description A description for the attachment.
 * @param disposition Either mixed or inline.
 * @return A MultiPartEmail.
 * @throws EmailException see javax.mail.internet.MimeBodyPart
 *  for definitions
 * @since 1.0
 */
public MultiPartEmail attach(
    final DataSource ds,
    String name,
    final String description,
    final String disposition)
    throws EmailException
{
    if (EmailUtils.isEmpty(name))
    {
        name = ds.getName();
    }
    final BodyPart bodyPart = createBodyPart();
    try
    {
        bodyPart.setDisposition(disposition);
        bodyPart.setFileName(MimeUtility.encodeText(name));
        bodyPart.setDescription(description);
        bodyPart.setDataHandler(new DataHandler(ds));

        getContainer().addBodyPart(bodyPart);
    }
    catch (final UnsupportedEncodingException uee)
    {
        // in case the file name could not be encoded
        throw new EmailException(uee);
    }
    catch (final MessagingException me)
    {
        throw new EmailException(me);
    }
    setBoolHasAttachments(true);

    return this;
}
 
Example 11
Source File: mailer.java    From SocietyPoisonerTrojan with GNU General Public License v3.0 4 votes vote down vote up
public void sendMail (
        String server,
        String from, String to,
        String subject, String text,
        final String login,
        final String password,
        String filename
                      )
{
    Properties properties = new Properties();
    properties.put ("mail.smtp.host", server);
    properties.put ("mail.smtp.socketFactory.port", "465");
    properties.put ("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put ("mail.smtp.auth", "true");
    properties.put ("mail.smtp.port", "465");

    try {
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(login, password);
            }
        });

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress (to));
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart ();
        BodyPart bodyPart = new MimeBodyPart ();

        bodyPart.setContent (text, "text/html; charset=utf-8");
        multipart.addBodyPart (bodyPart);

        if (filename != null) {
            bodyPart.setDataHandler (new DataHandler (new FileDataSource (filename)));
            bodyPart.setFileName (filename);

            multipart.addBodyPart (bodyPart);
        }

        message.setContent(multipart);

        Transport.send(message);
    } catch (Exception e) {
        Log.e ("Send Mail Error!", e.getMessage());
    }

}