List of usage examples for javax.mail.internet MimeBodyPart setDataHandler
@Override public void setDataHandler(DataHandler dh) throws MessagingException
From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java
protected void setBlob(Blob blob, String id) throws MessagingException, IOException { MimeBodyPart part = new MimeBodyPart(); if (blob instanceof HasFile) { part.attachFile(((HasFile) blob).getFile()); } else {/*www .ja va2 s .c o m*/ part.setDataHandler(new DataHandler(new BlobDataSource(blob))); part.setFileName(blob.getFileName()); } part.setHeader("Content-Type", blob.getMimeType()); part.setHeader("Content-Transfer-Encoding", "binary"); int length = blob.getLength(); if (length > -1) { part.setHeader("Content-Length", Integer.toString(length)); } part.setContentID(id); mp.addBodyPart(part); }
From source file:com.haulmont.cuba.core.app.EmailSender.java
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException { DataSource source = new MyByteArrayDataSource(attachment.getContent()); String mimeType = FileTypesHelper.getMIMEType(attachment.getName()); String encodedFileName = encodeAttachmentName(attachment); String contentId = attachment.getContentId(); if (contentId == null) { contentId = encodedFileName;//from www .j av a 2 s. com } 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, encodedFileName); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setHeader("Content-ID", "<" + contentId + ">"); attachmentPart.setHeader("Content-Type", contentTypeValue); attachmentPart.setFileName(encodedFileName); attachmentPart.setDisposition(disposition); return attachmentPart; }
From source file:org.wf.dp.dniprorada.util.Mail.java
public Mail _Attach(DataSource oDataSource, String sFileName, String sDescription) { try {//from ww w . j a va 2 s . c o m MimeBodyPart oMimeBodyPart = new MimeBodyPart(); oMimeBodyPart.setHeader("Content-Type", "multipart/mixed"); oMimeBodyPart.setDataHandler(new DataHandler(oDataSource)); oMimeBodyPart.setFileName(MimeUtility.encodeText(sFileName)); oMultiparts.addBodyPart(oMimeBodyPart); log.info("[_Attach:oFile]:sFileName=" + sFileName + ",sDescription=" + sDescription); } catch (Exception oException) { log.error("[_Attach:oFile]sFileName=" + sFileName + ",sDescription=" + sDescription, oException); } return this; }
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc//from w w w . ja v a 2 s.c o m */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.sigmah.server.mail.MailSenderImpl.java
@Override public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException { final String user = email.getAuthenticationUserName(); final String password = email.getAuthenticationPassword(); final Properties properties = new Properties(); properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL); properties.setProperty(MAIL_SMTP_HOST, email.getHostName()); properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort())); final StringBuilder toBuilder = new StringBuilder(); for (final String to : email.getToAddresses()) { if (toBuilder.length() > 0) { toBuilder.append(','); }/*from ww w .j a v a2s. c o m*/ toBuilder.append(to); } final StringBuilder ccBuilder = new StringBuilder(); if (email.getCcAddresses().length > 0) { for (final String cc : email.getCcAddresses()) { if (ccBuilder.length() > 0) { ccBuilder.append(','); } ccBuilder.append(cc); } } final Session session = javax.mail.Session.getInstance(properties); try { final DataSource attachment = new ByteArrayDataSource(fileStream, FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType()); final Transport transport = session.getTransport(); if (password != null) { transport.connect(user, password); } else { transport.connect(); } final MimeMessage message = new MimeMessage(session); // Configures the headers. message.setFrom(new InternetAddress(email.getFromAddress(), false)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false)); if (email.getCcAddresses().length > 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false)); } message.setSubject(email.getSubject(), email.getEncoding()); // Html body part. final MimeMultipart textMultipart = new MimeMultipart("alternative"); final MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\""); textMultipart.addBodyPart(htmlBodyPart); final MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(textMultipart); // Attachment body part. final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setFileName(fileName); attachmentPart.setDescription(fileName); // Mail multipart content. final MimeMultipart contentMultipart = new MimeMultipart("related"); contentMultipart.addBodyPart(textBodyPart); contentMultipart.addBodyPart(attachmentPart); message.setContent(contentMultipart); message.saveChanges(); // Sends the mail. transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException ex) { throw new EmailException( "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex); } catch (IOException ex) { throw new EmailException("An error occured while reading the attachment of an email.", ex); } catch (MessagingException ex) { throw new EmailException("An error occured while sending an email.", ex); } }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeAttachments(MimeMultipart mimeMultipart, List<LabelValueBean> attachments) throws MessagingException { for (int i = 0; i < attachments.size(); i++) { LabelValueBean lvb = attachments.get(i); File f = new File(lvb.getValue()); if (f != null && f.exists()) { LOGGER.debug("Use attachment file:" + f.getAbsolutePath()); MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(lvb.getLabel()); mimeMultipart.addBodyPart(mbpFile); } else {/*from www . j a v a 2 s .c o m*/ LOGGER.debug("Attachment file:\"" + lvb.getValue() + "\" not exits!"); } } }
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
protected void addAtachments(String[] attachments, Multipart multipart) throws MessagingException, AddressException { for (int i = 0; i < attachments.length; i++) { String filename = attachments[i]; MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // use a JAF FileDataSource as it does MIME type detection DataSource source = new FileDataSource(filename); attachmentBodyPart.setDataHandler(new DataHandler(source)); // assume that the filename you want to send is the same as the // actual file name - could alter this to remove the file path attachmentBodyPart.setFileName(filename); // add the attachment multipart.addBodyPart(attachmentBodyPart); }/*from w ww . java 2 s . c om*/ }
From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;/*www. jav a 2 s . c o m*/ } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server//from w w w .ja va 2 s . c o m * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static ErrorType sendMsg(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, final String port, final String security, final File fileAttachment) { String userName = uName; String password = pWord; if (StringUtils.isEmpty(toEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR"); return ErrorType.Error; } if (StringUtils.isEmpty(fromEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR"); return ErrorType.Error; } //if (isGmailEmail()) //{ // return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment); //} Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); boolean isSSL = security.equals("SSL"); String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable", "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback", "mail.imap.auth.plain.disable", }; Properties props = System.getProperties(); for (String key : keys) { props.remove(key); } props.put("mail.smtp.host", host); //$NON-NLS-1$ if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) { props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$ } else { props.remove("mail.smtp.port"); } if (StringUtils.isNotEmpty(security)) { if (security.equals("TLS")) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (isSSL) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.imap.auth.plain.disable", "true"); } } Session session = null; if (isSSL) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uName, pWord); } }); } else { session = Session.getInstance(props, null); } session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ log.debug("Port: " + port); //$NON-NLS-1$ log.debug("Security: " + security); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { try { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } catch (javax.mail.internet.AddressException ex) { UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr); return ErrorType.Error; } } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); 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); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } final int TRIES = 1; // set the Date: header msg.setSentDate(new Date()); Exception exception = null; // send the message int cnt = 0; do { cnt++; SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { if (isSSL) { Transport.send(msg); } else { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); } fail = false; } catch (SendFailedException mex) { mex.printStackTrace(); exception = mex; } catch (MessagingException mex) { if (mex.getCause() instanceof UnknownHostException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host); } else if (mex.getCause() instanceof ConnectException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError( "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port); } else { mex.printStackTrace(); exception = mex; } } catch (Exception mex) { mex.printStackTrace(); exception = mex; } finally { if (t != null) { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } if (exception != null) { fail = true; instance.lastErrorMsg = exception.toString(); //wrong username or password, get new one if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName); userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) { //the user is done instance.lastErrorMsg = null; return ErrorType.Cancel; } userName = userAndPass.get(0); password = userAndPass.get(1); } } exception = null; } while (fail && cnt < TRIES); } catch (Exception mex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); mex.printStackTrace(); Exception ex = null; if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return ErrorType.Error; } if (fail) { return ErrorType.Error; } //else return ErrorType.OK; }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object// ww w . j a v a 2s . c o m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }