List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:org.enlacerh.util.FileUploadController.java
/** * Mtodo que enva los recibos de pago a cada usuario * @throws IOException /*from w ww. ja va2 s .c om*/ * @throws NumberFormatException * **/ public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException { try { //System.out.println("Enviando recibo"); //System.out.println(jndimail()); Context initContext = new InitialContext(); Session session = (Session) initContext.lookup(jndimail()); // Crear el mensaje a enviar MimeMessage mm = new MimeMessage(session); // Establecer las direcciones a las que ser enviado // el mensaje (test2@gmail.com y test3@gmail.com en copia // oculta) // mm.setFrom(new // InternetAddress("opennomina@dvconsultores.com")); mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Establecer el contenido del mensaje mm.setSubject(getMessage("mailRP")); //mm.setText(getMessage("mailContent")); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = laruta + File.separator + file + ".pdf"; javax.activation.DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(file + ".pdf"); multipart.addBodyPart(messageBodyPart); // Send the complete message parts mm.setContent(multipart); // Enviar el correo electrnico Transport.send(mm); //System.out.println("Correo enviado exitosamente a :" + to); //System.out.println("Fin recibo"); } catch (Exception e) { msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, ""); FacesContext.getCurrentInstance().addMessage(null, msj); e.printStackTrace(); } }
From source file:com.photon.phresco.util.Utility.java
public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }//from ww w . j av a 2 s . c o m Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); DataSource source = new FileDataSource(body); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("Error.txt"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source2 = new FileDataSource(screen); messageBodyPart2.setDataHandler(new DataHandler(source2)); messageBodyPart2.setFileName("Error.jpg"); multipart.addBodyPart(messageBodyPart2); MimeBodyPart mainPart = new MimeBodyPart(); String content = "<b>Phresco framework error report<br><br>User Name: " + user + "<br> Email Address: " + fromAddr + "<br>Build No: " + build; mainPart.setContent(content, "text/html"); multipart.addBodyPart(mainPart); message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;//from w w w .ja v a 2 s .c o m try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null;//from w w w . j av a 2s. c om boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null; //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) { try {//from w w w . ja va 2 s . c o m Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); msg.setFrom(from); msg.setSubject(subject, "utf-8"); if (to != null) { msg.addRecipient(RecipientType.TO, to); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart(); // 1) add body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); // 2) add attachments for (DBMailAttachment attachment : attachments) { // abort if attachment does not exist if (attachment == null || attachment.getSize() <= 0) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null); return msg; } messageBodyPart = new MimeBodyPart(); VFSLeaf data = getAttachmentDatas(attachment); DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text msg.setText(body, "utf-8"); } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (MessagingException e) { logError("", e); return null; } }
From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {//from ww w . j av a 2 s . co m String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); String mailTos = ""; List dlIds = sInfo.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(biobj, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.auth", "true"); // create autheticator object Authenticator auth = new SMTPAuthenticator(user, pass); // open session Session session = Session.getDefaultInstance(props, auth); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); 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 IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = biobj.getName() + toBeAppendedToName; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(response, retCT, biobj.getName() + toBeAppendedToName + fileExt); 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 Transport.send(msg); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); } finally { logger.debug("OUT"); } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
@Override public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) { try {/* w w w .ja v a 2 s . c o m*/ // see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection. // following doesn't work correctly, therefore add bounce-address in message already Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"), WebappHelper.getMailConfig("mailFromName")); msg.setFrom(viewableFrom); msg.setSubject(subject, "utf-8"); // reply to can only be an address without name (at least for postfix!), see FXOLAT-312 msg.setReplyTo(new Address[] { convertedFrom }); if (tos != null && tos.length > 0) { msg.addRecipients(RecipientType.TO, tos); } if (ccs != null && ccs.length > 0) { msg.addRecipients(RecipientType.CC, ccs); } if (bccs != null && bccs.length > 0) { msg.addRecipients(RecipientType.BCC, bccs); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart("mixed"); // 1) add body part if (StringHelper.isHtml(body)) { Multipart alternativePart = createMultipartAlternative(body); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alternativePart); multipart.addBodyPart(wrap); } else { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } // 2) add attachments for (File attachmentFile : attachments) { // abort if attachment does not exist if (attachmentFile == null || !attachmentFile.exists()) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null); return msg; } BodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFile); filePart.setDataHandler(new DataHandler(source)); filePart.setFileName(attachmentFile.getName()); multipart.addBodyPart(filePart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text if (StringHelper.isHtml(body)) { msg.setContent(createMultipartAlternative(body)); } else { msg.setText(body, "utf-8"); } } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (AddressException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logError("", e); return null; } catch (UnsupportedEncodingException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
private Multipart createMultipartAlternative(String text) throws MessagingException { String pureText = new NekoHTMLFilter().filter(text, true); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(pureText, "utf-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setText(text, "utf-8", "html"); Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(textPart);//from ww w. ja v a 2s . co m multipart.addBodyPart(htmlPart); return multipart; }
From source file:org.kuali.test.utils.Utils.java
/** * //from w ww . ja v a 2 s . co m * @param configuration * @param overrideEmail * @param testSuite * @param testHeader * @param testResults * @param errorCount * @param warningCount * @param successCount */ public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration, String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults, int errorCount, int warningCount, int successCount) { if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress()) && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) { String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader); if (toAddresses.length > 0) { Properties props = new Properties(); props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost()); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress())); if (StringUtils.isBlank(overrideEmail)) { for (String recipient : toAddresses) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } else { StringTokenizer st = new StringTokenizer(overrideEmail, ","); while (st.hasMoreTokens()) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken())); } } StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject()); subject.append(" - Platform: "); if (testSuite != null) { subject.append(testSuite.getPlatformName()); subject.append(", TestSuite: "); subject.append(testSuite.getName()); } else { subject.append(testHeader.getPlatformName()); subject.append(", Test: "); subject.append(testHeader.getTestName()); } subject.append(" - [errors="); subject.append(errorCount); subject.append(", warnings="); subject.append(warningCount); subject.append(", successes="); subject.append(successCount); subject.append("]"); msg.setSubject(subject.toString()); StringBuilder msgtxt = new StringBuilder(256); msgtxt.append("Please see test output in the following attached files:\n"); for (File f : testResults) { msgtxt.append(f.getName()); msgtxt.append("\n"); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgtxt.toString()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); for (File f : testResults) { if (f.exists() && f.isFile()) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.setDataHandler(new DataHandler(new FileDataSource(f))); mbp2.setFileName(f.getName()); mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException ex) { LOG.warn(ex.toString(), ex); } } } }
From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java
@Override public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) { //<editor-fold defaultstate="collapsed" desc="Inicio"> LOGGER.info("Iniciando el metodo obtenerCotizacionInternet..."); OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO(); String codigo;/* www. j a v a 2s . c o m*/ String mensaje; XStream xStream = new XStream(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Validacion de entrada"> OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input); if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) { codigo = Integer.toString(outputValidacion.getCodigo()); mensaje = outputValidacion.getMensaje(); LOGGER.info(mensaje); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer"> String numeroCotizacion = input.getNumeroCotizacion(); InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet(); inputCotizacionInternet.setIdCotizacion(numeroCotizacion); String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet); LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet); servicioJasperServer = new ServicioJasperServerJerseyImpl(); ResultadoDocumentoVO outputJasperServer; try { outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet); String xmlOutputJasperServer = xStream.toXML(outputJasperServer); LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer); String codigoJasperServer = outputJasperServer.getCodigo(); if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida"> ClienteServicioCotizadorVida clienteCotizadorVida; try { clienteCotizadorVida = new ClienteServicioCotizadorVida(); } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //Se busca el nombre del asegurado, glosa del plan y numero de propuesta LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet); OutputEmailCotizacionInternetVO outputEmail; try { outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet); String xmlOutputEmail = xStream.toXML(outputEmail); LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail); String codigoOutputEmail = outputEmail.getCodigo(); if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.info(mensaje + ": " + outputEmail.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto"> String documento = outputJasperServer.getDocumento(); try { EmailVO datosEmail = outputEmail.getDatosEmail(); String htmlBody = Propiedades.getFuncProperty("email.html"); String nombreAsegurable = datosEmail.getNombreAsegurable(); if (nombreAsegurable == null) { nombreAsegurable = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable); String glosaPlan = datosEmail.getGlosaPlan(); if (glosaPlan == null) { glosaPlan = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan); String numeroPropuesta = datosEmail.getNumeroPropuesta(); if (numeroPropuesta == null) { numeroPropuesta = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta); //Parametrizar imagenes String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde"); if (imgBulletBgVerde == null) { imgBulletBgVerde = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde); String imgFace = Propiedades.getFuncProperty("email.images.face"); if (imgFace == null) { imgFace = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace); String imgTwitter = Propiedades.getFuncProperty("email.images.twitter"); if (imgTwitter == null) { imgTwitter = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter); String imgYoutube = Propiedades.getFuncProperty("email.images.youtube"); if (imgYoutube == null) { imgYoutube = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube); String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115"); if (imgMail15 == null) { imgMail15 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15); String imgFono = Propiedades.getFuncProperty("email.images.fono"); if (imgFono == null) { imgFono = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono); String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116"); if (imgMail16 == null) { imgMail16 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16); byte[] attachmentData = Base64.decodeBase64(documento); final String username = Propiedades.getKeyProperty("email.username"); final String encryptedPassword = Propiedades.getKeyProperty("email.password"); String privateKeyFile = Propiedades.getConfProperty("KEY"); CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile); final String password = cryptoUtil.decryptData(encryptedPassword); final String auth = Propiedades.getFuncProperty("email.auth"); final String starttls = Propiedades.getFuncProperty("email.starttls"); final String host = Propiedades.getFuncProperty("email.host"); final String port = Propiedades.getFuncProperty("email.port"); //Log de datos de correo String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host + "\n"; LOGGER.info("Datos correo: \n".concat(strDatosCorreo)); Properties props = new Properties(); props.put("mail.smtp.auth", auth); if (!"0".equals(starttls)) { props.put("mail.smtp.starttls.enable", starttls); } props.put("mail.smtp.host", host); if (!"0".equals(port)) { props.put("mail.smtp.port", port); } Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name"); fileName = fileName.replaceAll("%s", numeroPropuesta); fileName = fileName + ".pdf"; // creates a new e-mail message Message msg = new MimeMessage(session); String from = Propiedades.getFuncProperty("email.from"); msg.setFrom(new InternetAddress(from)); //TODO considerar email de prueba o email del asegurado String emailTo; if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) { emailTo = Propiedades.getFuncProperty("email.to.mail"); } else { emailTo = datosEmail.getEmail(); } InternetAddress[] toAddresses = { new InternetAddress(emailTo) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); String subject = Propiedades.getFuncProperty("email.subject"); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(htmlBody, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments MimeBodyPart attachPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf"); attachPart.setDataHandler(new DataHandler(dataSource)); attachPart.setFileName(fileName); multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); } catch (Exception ex) { codigo = Propiedades.getFuncProperty("email.error.codigo"); mensaje = Propiedades.getFuncProperty("email.error.mensaje"); LOGGER.error(mensaje + ": " + ex.getMessage(), ex); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Termino"> codigo = Propiedades.getFuncProperty("codigo.ok"); mensaje = Propiedades.getFuncProperty("mensaje.ok"); output.setCodigo(codigo); output.setMensaje(mensaje); return output; //</editor-fold> }