Java Code Examples for javax.activation.DataSource

The following examples show how to use javax.activation.DataSource. These examples are extracted from open source projects. 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 Project: cuba   Source File: EmailSender.java    License: Apache License 2.0 6 votes vote down vote up
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
    DataSource source = new MyByteArrayDataSource(attachment.getContent());

    String mimeType = FileTypesHelper.getMIMEType(attachment.getName());

    String contentId = attachment.getContentId();
    if (contentId == null) {
        contentId = generateAttachmentContentId(attachment.getName());
    }

    String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
    String charset = MimeUtility.mimeCharset(attachment.getEncoding() != null ?
            attachment.getEncoding() : StandardCharsets.UTF_8.name());
    String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, attachment.getName());

    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(source));
    attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
    attachmentPart.setHeader("Content-Type", contentTypeValue);
    attachmentPart.setFileName(attachment.getName());
    attachmentPart.setDisposition(disposition);

    return attachmentPart;
}
 
Example 2
Source Project: commons-email   Source File: EmailLiveTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This test checks the correct character encoding when sending
 * non-ASCII content using SimpleEmail.
 *
 * https://issues.apache.org/jira/browse/EMAIL-79
 *
 * @throws Exception the test failed
 */
@Test
public void testCorrectCharacterEncoding() throws Exception
{
    // U+03B1 : GREEK SMALL LETTER ALPHA
    // U+03B2 : GREEK SMALL LETTER BETA
    // U+03B3 : GREEK SMALL LETTER GAMMA

    final String subject = "[email] 5.Test: Subject with three greek UTF-8 characters : \u03B1\u03B2\u03B3";
    final String textMsg = "My test body with with three greek UTF-8 characters : \u03B1\u03B2\u03B3\n";
    final String attachmentName = "\u03B1\u03B2\u03B3.txt";

    // make sure to set the charset before adding the message content
    final MultiPartEmail email = (MultiPartEmail) create(MultiPartEmail.class);
    email.setSubject(subject);
    email.setMsg(textMsg);

    // create a proper UTF-8 sequence for the text attachment (matching our default charset)
    final DataSource attachment = new javax.mail.util.ByteArrayDataSource(textMsg.getBytes("utf-8"), "text/plain");
    email.attach(attachment, attachmentName, "Attachment in Greek");

    EmailUtils.writeMimeMessage( new File("./target/test-emails/correct-encoding.eml"), send(email).getMimeMessage());
}
 
Example 3
Source Project: openjdk-jdk9   Source File: SOAPPartImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
DataHandler getDataHandler() {
    DataSource ds = new DataSource() {
        @Override
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Illegal Operation");
        }

        @Override
        public String getContentType() {
            return getContentTypeString();
        }

        @Override
        public String getName() {
            return getContentId();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return getContentAsStream();
        }
    };
    return new DataHandler(ds);
}
 
Example 4
Source Project: robe   Source File: MailItemTest.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void constructorAndToStringAndHash() throws Exception {
    MailItem item1 = new MailItem("title", "body", (DataSource) null, "sender", "receiver");
    MailItem item2 = new MailItem("title", "body", (DataSource) null , "sender", Arrays.asList("receiver"));
    item1.setId("1");
    item2.setId("1");
    assertEquals(item1, item2);

    MailItem item3 = new MailItem("title", "body", (List<DataSource>) null, "sender", "receiver");
    MailItem item4 = new MailItem("title", "body", (List<DataSource>) null , "sender", Arrays.asList("receiver"));
    item3.setId("1");
    item4.setId("1");
    assertEquals(item3, item4);
    assertEquals(item1.toString(),item2.toString());
    assertEquals(item1.hashCode(),item2.hashCode());
}
 
Example 5
private ContentType encode(MessageDataSource mds, OutputStream out) {
    try {
        final boolean isFastInfoset = XMLMessage.isFastInfoset(
                mds.getDataSource().getContentType());
        DataSource ds = transformDataSource(mds.getDataSource(),
                isFastInfoset, useFastInfosetForEncoding, features);

        InputStream is = ds.getInputStream();
        byte[] buf = new byte[1024];
        int count;
        while((count=is.read(buf)) != -1) {
            out.write(buf, 0, count);
        }
        return new ContentTypeImpl(ds.getContentType());
    } catch(IOException ioe) {
        throw new WebServiceException(ioe);
    }
}
 
Example 6
Source Project: TencentKona-8   Source File: SOAPPartImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
DataHandler getDataHandler() {
    DataSource ds = new DataSource() {
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Illegal Operation");
        }

        public String getContentType() {
            return getContentTypeString();
        }

        public String getName() {
            return getContentId();
        }

        public InputStream getInputStream() throws IOException {
            return getContentAsStream();
        }
    };
    return new DataHandler(ds);
}
 
Example 7
Source Project: openjdk-jdk9   Source File: BMMimeMultipart.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a MimeMultipart object and its bodyparts from the
 * given DataSource. <p>
 *
 * This constructor handles as a special case the situation where the
 * given DataSource is a MultipartDataSource object.  In this case, this
 * method just invokes the superclass (i.e., Multipart) constructor
 * that takes a MultipartDataSource object. <p>
 *
 * Otherwise, the DataSource is assumed to provide a MIME multipart
 * byte stream.  The <code>parsed</code> flag is set to false.  When
 * the data for the body parts are needed, the parser extracts the
 * "boundary" parameter from the content type of this DataSource,
 * skips the 'preamble' and reads bytes till the terminating
 * boundary and creates MimeBodyParts for each part of the stream.
 *
 * @param   ct  content type.
 * @param   ds  DataSource, can be a MultipartDataSource.
 * @throws  MessagingException in case of error.
 */
public BMMimeMultipart(DataSource ds, ContentType ct)
        throws MessagingException {
    super(ds, ct);
    boundary = ct.getParameter("boundary");
    /*
if (ds instanceof MultipartDataSource) {
    // ask super to do this for us.
    setMultipartDataSource((MultipartDataSource)ds);
    return;
}

// 'ds' was not a MultipartDataSource, we have
// to parse this ourself.
parsed = false;
this.ds = ds;
    if (ct==null)
        contentType = new ContentType(ds.getContentType());
    else
        contentType = ct;
   */

}
 
Example 8
Source Project: openjdk-jdk8u   Source File: Stubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new {@link Dispatch} stub that connects to the given pipe.
 *
 * @param portInfo
 *      see <a href="#param">common parameters</a>
 * @param owner
 *      see <a href="#param">common parameters</a>
 * @param binding
 *      see <a href="#param">common parameters</a>
 * @param clazz
 *      Type of the {@link Dispatch} to be created.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param mode
 *      The mode of the dispatch.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param epr
 *      see <a href="#param">common parameters</a>
 * TODO: are these parameters making sense?
 */
public static <T> Dispatch<T> createDispatch(WSPortInfo portInfo,
                                             WSService owner,
                                             WSBinding binding,
                                             Class<T> clazz, Service.Mode mode,
                                             @Nullable WSEndpointReference epr) {
    if (clazz == SOAPMessage.class) {
        return (Dispatch<T>) createSAAJDispatch(portInfo, binding, mode, epr);
    } else if (clazz == Source.class) {
        return (Dispatch<T>) createSourceDispatch(portInfo, binding, mode, epr);
    } else if (clazz == DataSource.class) {
        return (Dispatch<T>) createDataSourceDispatch(portInfo, binding, mode, epr);
    } else if (clazz == Message.class) {
        if(mode==Mode.MESSAGE)
            return (Dispatch<T>) createMessageDispatch(portInfo, binding, epr);
        else
            throw new WebServiceException(mode+" not supported with Dispatch<Message>");
    } else if (clazz == Packet.class) {
        if(mode==Mode.MESSAGE)
            return (Dispatch<T>) createPacketDispatch(portInfo, binding, epr);
        else
            throw new WebServiceException(mode+" not supported with Dispatch<Packet>");
    } else
        throw new WebServiceException("Unknown class type " + clazz.getName());
}
 
Example 9
Source Project: openjdk-jdk9   Source File: Stubs.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new {@link Dispatch} stub that connects to the given pipe.
 *
 * @param portName
 *      see {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param owner
 *      see <a href="#param">common parameters</a>
 * @param binding
 *      see <a href="#param">common parameters</a>
 * @param clazz
 *      Type of the {@link Dispatch} to be created.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param mode
 *      The mode of the dispatch.
 *      See {@link Service#createDispatch(QName, Class, Service.Mode)}.
 * @param next
 *      see <a href="#param">common parameters</a>
 * @param epr
 *      see <a href="#param">common parameters</a>
 * TODO: are these parameters making sense?
 */
@SuppressWarnings("unchecked")
    public static <T> Dispatch<T> createDispatch(QName portName,
                                             WSService owner,
                                             WSBinding binding,
                                             Class<T> clazz, Service.Mode mode, Tube next,
                                             @Nullable WSEndpointReference epr) {
    if (clazz == SOAPMessage.class) {
        return (Dispatch<T>) createSAAJDispatch(portName, owner, binding, mode, next, epr);
    } else if (clazz == Source.class) {
        return (Dispatch<T>) createSourceDispatch(portName, owner, binding, mode, next, epr);
    } else if (clazz == DataSource.class) {
        return (Dispatch<T>) createDataSourceDispatch(portName, owner, binding, mode, next, epr);
    } else if (clazz == Message.class) {
        if(mode==Mode.MESSAGE)
            return (Dispatch<T>) createMessageDispatch(portName, owner, binding, next, epr);
        else
            throw new WebServiceException(mode+" not supported with Dispatch<Message>");
    } else if (clazz == Packet.class) {
        return (Dispatch<T>) createPacketDispatch(portName, owner, binding, next, epr);
    } else
        throw new WebServiceException("Unknown class type " + clazz.getName());
}
 
Example 10
/**
 * Create an object from the input stream
 */
public Object getContent(DataSource ds) throws IOException {
    String ctStr = ds.getContentType();
    String charset = null;
    if (ctStr != null) {
        ContentType ct = new ContentType(ctStr);
        if (!isXml(ct)) {
            throw new IOException(
                "Cannot convert DataSource with content type \""
                        + ctStr + "\" to object in XmlDataContentHandler");
        }
        charset = ct.getParameter("charset");
    }
    return (charset != null)
            ? new StreamSource(new InputStreamReader(ds.getInputStream()), charset)
            : new StreamSource(ds.getInputStream());
}
 
Example 11
Source Project: cxf   Source File: AttachmentDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
private void cacheStreamedAttachments() throws IOException {
    if (body instanceof DelegatingInputStream
        && !((DelegatingInputStream) body).isClosed()) {

        cache((DelegatingInputStream) body);
    }

    List<Attachment> atts = new ArrayList<>(attachments.getLoadedAttachments());
    for (Attachment a : atts) {
        DataSource s = a.getDataHandler().getDataSource();
        if (s instanceof AttachmentDataSource) {
            AttachmentDataSource ads = (AttachmentDataSource)s;
            if (!ads.isCached()) {
                ads.cache(message);
            }
        } else if (s.getInputStream() instanceof DelegatingInputStream) {
            cache((DelegatingInputStream) s.getInputStream());
        } else {
            //assume a normal stream that is already cached
        }
    }
}
 
Example 12
Source Project: hottub   Source File: XMLHTTPBindingCodec.java    License: GNU General Public License v2.0 6 votes vote down vote up
private ContentType encode(MessageDataSource mds, OutputStream out) {
    try {
        final boolean isFastInfoset = XMLMessage.isFastInfoset(
                mds.getDataSource().getContentType());
        DataSource ds = transformDataSource(mds.getDataSource(),
                isFastInfoset, useFastInfosetForEncoding, features);

        InputStream is = ds.getInputStream();
        byte[] buf = new byte[1024];
        int count;
        while((count=is.read(buf)) != -1) {
            out.write(buf, 0, count);
        }
        return new ContentTypeImpl(ds.getContentType());
    } catch(IOException ioe) {
        throw new WebServiceException(ioe);
    }
}
 
Example 13
Source Project: sakai   Source File: BasicEmailService.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Attaches a file as a body part to the multipart message
 *
 * @param attachment
 * @throws MessagingException
 */
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException
{
	DataSource source = attachment.getDataSource();
	MimeBodyPart attachPart = new MimeBodyPart();

	attachPart.setDataHandler(new DataHandler(source));
	attachPart.setFileName(attachment.getFilename());

	if (attachment.getContentTypeHeader() != null) {
		attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
	}

	if (attachment.getContentDispositionHeader() != null) {
		attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
	}

	return attachPart;
}
 
Example 14
Source Project: cxf   Source File: DataSourceTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void inputStreamShouldBeClosedOnReadingException() throws Exception {
    DataSource ds = mock(MockType.STRICT, DataSource.class);
    InputStream is = mock(MockType.STRICT, InputStream.class);
    expect(ds.getInputStream()).andReturn(is);
    replay(ds);
    expect(is.available()).andThrow(new IOException());
    is.close();
    replay(is);

    DataSourceType dst = new DataSourceType(false, null);
    try {
        dst.getBytes(ds);
    } finally {
        verify(ds);
        verify(is);
    }

}
 
Example 15
Source Project: smart-admin   Source File: SmartSendMailUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param sendMail 发件人邮箱
 * @param sendMailPwd 发件人密码
 * @param sendMailName 发件人昵称(可选)
 * @param receiveMail 收件人邮箱
 * @param receiveMailName 收件人昵称(可选)
 * @param sendSMTPHost 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
 * @param title 邮件主题
 * @param content 邮件正文
 * @author Administrator
 * @date 2017年12月13日 下午1:51:38
 */
public static void sendFileMail(String sendMail, String sendMailPwd, String sendMailName, String[] receiveMail, String receiveMailName, String sendSMTPHost, String title, String content,
                                InputStream is, String fileName, String port) {

    Session session = createSSLSession(sendSMTPHost, port, sendMailName, sendMailPwd);
    // 3. 创建一封邮件
    MimeMessage message;
    try {
        message = createMimeMessage(session, sendMail, sendMailName, receiveMail, receiveMailName, title, content);
        // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
        MimeMultipart mm = new MimeMultipart();
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");
        mm.addBodyPart(text);
        if (null != is && is.available() > 0) {
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(is, "application/msexcel");
            // 将附件数据添加到"节点"
            attachment.setDataHandler(new DataHandler(source));
            // 设置附件的文件名(需要编码)
            attachment.setFileName(MimeUtility.encodeText(fileName));
            // 10. 设置文本和 附件 的关系(合成一个大的混合"节点" / Multipart )
            // 如果有多个附件,可以创建多个多次添加
            mm.addBodyPart(attachment);
        }
        message.setContent(mm);
        message.saveChanges();
        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport("smtp");
        transport.connect(sendSMTPHost, sendMail, sendMailPwd);
        //            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        // 7. 关闭连接
    } catch (Exception e) {
        log.error("", e);
    }

}
 
Example 16
/**
 * Return the Transfer Data of type DataFlavor from InputStream.
 *
 * @param df The DataFlavor
 * @param ds The DataSource corresponding to the data
 * @return String object
 */
public Object getTransferData(DataFlavor df, DataSource ds)
        throws IOException {
    // use myDF.equals to be sure to get ActivationDataFlavor.equals,
    // which properly ignores Content-Type parameters in comparison
    if (getDF().equals(df))
        return getContent(ds);
    else
        return null;
}
 
Example 17
Source Project: lemon   Source File: LocalInternalStoreConnector.java    License: Apache License 2.0 5 votes vote down vote up
public StoreDTO saveStore(String model, DataSource dataSource,
        String tenantId) throws Exception {
    StoreResult storeResult = storeHelper.saveStore(tenantId + "/" + model,
            dataSource);

    return this.convertStoreDto(storeResult);
}
 
Example 18
Source Project: cf-butler   Source File: JavaMailNotifier.java    License: Apache License 2.0 5 votes vote down vote up
private static void addAttachment(MimeMessageHelper helper, EmailAttachment ea) {
    try {
        DataSource ds = new ByteArrayDataSource(ea.getHeadedContent(), ea.getMimeType());
        helper.addAttachment(ea.getFilename() + ea.getExtension(), ds);
    } catch (MessagingException | IOException e) {
        log.warn("Could not add attachment to email!", e);
    }
}
 
Example 19
@CoverageIgnore
private void sendEmail(MailInfo info, DataSource attachment, String body, JobSpec currJob) {
  Message message = new MimeMessage(session);
  List<Address> to = new ArrayList<>();
  try {
    List<String> resultEmails = currJob.getResultEmail();
    if (resultEmails.size() == 0) {
      return;
    }
    message.setFrom(new InternetAddress(info.from));
    for (String s : resultEmails) {
      for (Address ad : InternetAddress.parse(s)) {
        to.add(ad);
      }
    }
    message.setRecipients(Message.RecipientType.TO,
      to.toArray(new Address[]{}));
    message.setSubject("Chronos " + currJob.getName());
    Multipart multipart = new MimeMultipart();
    {
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(body, "text/html");
      multipart.addBodyPart(messageBodyPart);
    }
    {
      MimeBodyPart attachmentPart = new MimeBodyPart();
      attachmentPart.setDataHandler(new DataHandler(attachment));
      String fileName = String.format("%s-%s.tsv",
          currJob.getName(), DT_FMT.print(plannedJob.getReplaceTime()));
      attachmentPart.setFileName(fileName);
      multipart.addBodyPart(attachmentPart);
    }
    message.setContent(multipart);
    Transport.send(message);
    LOG.info("Sent email to: " + to);
  } catch (MessagingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 20
private void addAttachments(Message message, List<DataSource> attachments) {

    if (attachments == null) {
      return;
    }

    for (DataSource source : attachments) {
      try {
        InputStream stream = source.getInputStream();
        metaFiles.attach(stream, source.getName(), message);
      } catch (IOException e) {
        TraceBackService.trace(e);
      }
    }
  }
 
Example 21
Source Project: openjdk-8   Source File: DataSourceSource.java    License: GNU General Public License v2.0 5 votes vote down vote up
public DataSourceSource(DataSource source) throws MimeTypeParseException {
    this.source = source;

    String ct = source.getContentType();
    if(ct==null) {
        charset = null;
    } else {
        MimeType mimeType = new MimeType(ct);
        this.charset = mimeType.getParameter("charset");
    }
}
 
Example 22
Source Project: serianalyzer   Source File: ByteDataSource.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param ds
 * @throws IOException
 */
public ByteDataSource ( DataSource ds ) throws IOException {
    try ( InputStream is = ds.getInputStream() ) {
        int read;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte buffer[] = new byte[4096];
        while ( ( read = is.read(buffer) ) > 0 ) {
            bos.write(buffer, 0, read);
        }
        this.data = bos.toByteArray();
    }
}
 
Example 23
Source Project: cxf   Source File: MessageModeInInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    BindingOperationInfo bop = message.getExchange().getBindingOperationInfo();
    if (bop == null || !bindingName.equals(bop.getBinding().getName())) {
        return;
    }
    Object o = message.getContent(soapMsgClass);
    if (o != null) {
        doFromSoapMessage(message, o);
    } else if (DataSource.class.isAssignableFrom(type)) {
        doDataSource(message);
    }

}
 
Example 24
Source Project: robe   Source File: MailItemTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void getAttachments() throws Exception {
    List<DataSource> sources = new LinkedList<DataSource>();
    sources.add(new ByteArrayDataSource("attachment1", "text"));
    sources.add(new ByteArrayDataSource("attachment2", "text"));

    item.setAttachments(sources);
    assertEquals(sources, item.getAttachments());
}
 
Example 25
private void processDataSource(OutputStream outputStream, DataSource dataSource, ProgressReporter progressReporter) throws Exception {
	if (dataSource instanceof ExtendedDataSource) {
		((ExtendedDataSource) dataSource).writeToOutputStream(outputStream, progressReporter);
	} else {
		throw new SerializerException("Unsupported datasource type: " + dataSource);
	}
}
 
Example 26
Source Project: robe   Source File: MailItemTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void equalsTest(){
    MailItem item1 = new MailItem("title", "body", (DataSource) null, "sender", "receiver");
    assertEquals(item1, item1);

    Object item2 = new Object();
    assertNotEquals(item1,item2);

}
 
Example 27
Source Project: hottub   Source File: MimePullMultipart.java    License: GNU General Public License v2.0 5 votes vote down vote up
public MimePullMultipart(DataSource ds, ContentType ct)
    throws MessagingException {
    parsed = false;
    if (ct==null)
        contType = new ContentType(ds.getContentType());
    else
        contType = ct;

    dataSource = ds;
    boundary = contType.getParameter("boundary");
}
 
Example 28
/**
 * Returns an object which represents the data to be transferred.
 * The class of the object returned is defined by the representation class
 * of the flavor.
 *
 * @param df The DataFlavor representing the requested type.
 * @param ds The DataSource representing the data to be converted.
 * @return The constructed Object.
 */
public Object getTransferData(DataFlavor df, DataSource ds)
    throws IOException {
    for (DataFlavor aFlavor : flavor) {
        if (aFlavor.equals(df)) {
            return getContent(ds);
        }
    }
    return null;
}
 
Example 29
Source Project: activiti6-boot2   Source File: MailActivityBehavior.java    License: Apache License 2.0 5 votes vote down vote up
protected void attach(Email email, List<File> files, List<DataSource> dataSources) throws EmailException {
  if (!(email instanceof MultiPartEmail && attachmentsExist(files, dataSources))) {
    return;
  }
  MultiPartEmail mpEmail = (MultiPartEmail) email;
  for (File file : files) {
    mpEmail.attach(file);
  }
  for (DataSource ds : dataSources) {
    if (ds != null) {
      mpEmail.attach(ds, ds.getName(), null);
    }
  }
}
 
Example 30
Source Project: vocefiscal-android   Source File: GMailSender.java    License: 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); 
 }

}