List of usage examples for javax.mail.internet MimeBodyPart setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:au.aurin.org.controller.RestController.java
public Boolean sendEmail(final String randomUUIDString, final String password, final String email, final List<String> lstApps, final String fullName) throws IOException { final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString; logger.info("Starting sending Email to:" + email); String msg = ""; if (!fullName.equals("")) { msg = msg + "Dear " + fullName + "<br>"; }/*ww w .j a v a 2 s .c om*/ Boolean lswWhatIf = false; if (lstApps != null) { //msg = msg + "You have been given access to the following applications: <br>"; msg = msg + "<br>You have been given access to the following applications: <br>"; for (final String st : lstApps) { if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) { lswWhatIf = true; } msg = "<br>" + msg + st + "<br>"; } } msg = msg + "<br>Your current password is : " + password + " <br> To customise the password please change it using link below: <br> <a href='" + clink + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. "; final String subject = "AURIN Workbench Access"; final String from = classmail.getFrom(); final String to = email; if (lswWhatIf == true) { msg = msg + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au"; msg = msg + "<br>For other related requests please contact one of the members of the project team."; msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The Online WhatIf team<br>"; msg = msg + "<br><strong>Prof Christopher Pettit</strong> Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)"; msg = msg + "<br><strong>Claudia Pelizaro</strong> Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)"; msg = msg + "<br><strong>Andrew Dingjan</strong> Director, AURIN (andrew.dingjan@unimelb.edu.au)"; msg = msg + "<br><strong>Serryn Eagleson</strong> Manager Data and Business Analytics (serrynle@unimelb.edu.au)"; } else { msg = msg + "<br><br>Kind Regards,"; msg = msg + "<br>The AURIN Workbench team"; } try { final Message message = new MimeMessage(getSession()); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.addFrom(new InternetAddress[] { new InternetAddress(from) }); message.setSubject(subject); message.setContent(msg, "text/html"); ////////////////////////////////// final MimeMultipart multipart = new MimeMultipart("related"); final BodyPart messageBodyPart = new MimeBodyPart(); //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />"; //msg = msg + "<img src=\"cid:image\">"; messageBodyPart.setContent(msg, "text/html"); // add it multipart.addBodyPart(messageBodyPart); /////// second part (the image) // messageBodyPart = new MimeBodyPart(); final URL peopleresource = getClass().getResource("/logo.jpg"); logger.info(peopleresource.getPath()); // final DataSource fds = new FileDataSource( // peopleresource.getPath()); // // messageBodyPart.setDataHandler(new DataHandler(fds)); // messageBodyPart.setHeader("Content-ID", "<image>"); // // add image to the multipart // //multipart.addBodyPart(messageBodyPart); /////////// final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(peopleresource.getPath()); // final String cid = "1"; // imagePart.setContentID("<" + cid + ">"); imagePart.setHeader("Content-ID", "AbcXyz123"); imagePart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(imagePart); // put everything together message.setContent(multipart); //////////////////////////////// Transport.send(message); logger.info("Email sent to:" + email); } catch (final Exception mex) { logger.info(mex.toString()); return false; } return true; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed message. If the transfer mode is unencrypted/unsigned, a new Bodypart will be constructed *@return the payload part, this is important to compute the MIC later *//* www . ja v a2 s . co m*/ private Part verifySignature(AS2Message message, Partner sender, String contentType) throws Exception { if (this.certificateManagerSignature == null) { throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "AS2MessageParser.verifySignature: pass a certification manager for the signature before calling verifySignature()", message); } AS2Info as2Info = message.getAS2Info(); if (!as2Info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) as2Info; if (messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { InputStream memIn = message.getDecryptedRawDataInputStream(); MimeBodyPart testPart = new MimeBodyPart(memIn); memIn.close(); contentType = testPart.getContentType(); } } Part signedPart = this.getSignedPart(message.getDecryptedRawData(), contentType); //part is NOT signed but is defined to be signed if (signedPart == null) { as2Info.setSignType(AS2Message.SIGNATURE_NONE); if (as2Info.isMDN()) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.notsigned", as2Info.getMessageId()), as2Info); //MDN is not signed but should be signed if (sender.isSignedMDN()) { this.logger.log(Level.SEVERE, this.rb.getResourceString("mdn.unsigned.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } else { this.logger.log(Level.INFO, this.rb.getResourceString("msg.notsigned", as2Info.getMessageId()), as2Info); } if (!as2Info.isMDN() && sender.getSignType() != AS2Message.SIGNATURE_NONE) { throw new AS2Exception(AS2Exception.INSUFFICIENT_SECURITY_ERROR, "Incoming messages from AS2 partner " + sender.getAS2Identification() + " are defined to be signed.", message); } //if the message has been unsigned it is required to set a new datasource MimeBodyPart unsignedPart = new MimeBodyPart(); unsignedPart.setDataHandler( new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType))); unsignedPart.setHeader("content-type", contentType); return (unsignedPart); } else { //it is definitly a signed mdn if (as2Info.isMDN()) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.signed", as2Info.getMessageId()), as2Info); } as2Info.setSignType(this.getDigestFromSignature(signedPart)); //MDN is signed but shouldn't be signed' if (!sender.isSignedMDN()) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("mdn.signed.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } } else { //its no MDN, its a AS2 message if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("msg.signed", as2Info.getMessageId()), as2Info); } int signDigest = this.getDigestFromSignature(signedPart); String digest = null; if (signDigest == AS2Message.SIGNATURE_SHA1) { digest = "SHA1"; } else if (signDigest == AS2Message.SIGNATURE_MD5) { digest = "MD5"; } as2Info.setSignType(signDigest); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("signature.analyzed.digest", new Object[] { as2Info.getMessageId(), digest }), as2Info); } } } MimeBodyPart payloadPart = null; try { String signAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1()); payloadPart = this.verifySignedPartUsingAlias(message, signAlias, signedPart, contentType); } catch (AS2Exception e) { //retry to verify the signature with the second certificate if this is possible String secondAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1(2)); if (secondAlias != null) { payloadPart = this.verifySignedPartUsingAlias(message, secondAlias, signedPart, contentType); } else { throw e; } } return (payloadPart); }
From source file:lucee.runtime.net.smtp.SMTPClient.java
public MimeBodyPart toMimeBodyPart(Multipart mp, lucee.runtime.config.Config config, Attachment att) throws MessagingException { MimeBodyPart mbp = new MimeBodyPart(); // set Data Source String strRes = att.getAbsolutePath(); if (!StringUtil.isEmpty(strRes)) { mbp.setDataHandler(new DataHandler(new ResourceDataSource(config.getResource(strRes)))); } else//from w w w .j a v a 2 s. c o m mbp.setDataHandler(new DataHandler(new URLDataSource2(att.getURL()))); mbp.setFileName(att.getFileName()); if (!StringUtil.isEmpty(att.getType())) mbp.setHeader("Content-Type", att.getType()); if (!StringUtil.isEmpty(att.getDisposition())) { mbp.setDisposition(att.getDisposition()); /*if(mp instanceof MimeMultipart) { ((MimeMultipart)mp).setSubType("related"); }*/ } if (!StringUtil.isEmpty(att.getContentID())) mbp.setContentID(att.getContentID()); return mbp; }
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. j a v a 2s . co 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:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }//from w w w . j a v a 2 s.co m }); String title = "You have an invitation from your friend."; JsonObject jsonObject = gson.fromJson(data, JsonObject.class); String content = jsonObject.get("content").getAsString(); JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray(); ArrayList<String> listEmail = new ArrayList<>(); if (sportsArray != null) { for (int i = 0; i < sportsArray.size(); i++) { listEmail.add(sportsArray.get(i).getAsString()); } } String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); String addresses = ""; for (int i = 0; i < listEmail.size(); i++) { if (i < listEmail.size() - 1) { addresses = addresses + listEmail.get(i) + ","; } else { addresses = addresses + listEmail.get(i); } } message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses)); message.setSubject(title); message.setContent(mp); message.saveChanges(); try { Transport.send(message); } catch (Exception e) { e.printStackTrace(); } System.out.println("sent"); return true; }
From source file:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtpm.csloxinfo.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/* ww w . java 2 s. co m*/ }); //Create data for referral java.util.Date date = new java.util.Date(); String s = providerID + (new Timestamp(date.getTime()).toString()); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } m.update(s.getBytes(), 0, s.length()); String md5 = (new BigInteger(1, m.digest()).toString(16)); String title = "You have an invitation from your friend."; String receiver = request.getParameter("email"); // StringBuilder messageContentHtml = new StringBuilder(); // messageContentHtml.append(request.getParameter("message") + "<br />\n"); // messageContentHtml.append("You can become a provider from here: " + baseUrl + "/Common/Provider/SignupReferral/" + md5); // String messageContent = messageContentHtml.toString(); String emailContent = " <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>" + " <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>" + providerName + "</b> has invited you to complete purchase via</p>" + " <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5 + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;" + " background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>" + " <p style='font-size:16px;margin:30px;'><b>" + providerName + "</b> will get 25 credit</p>" + " <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>" + " <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>" + " " + " " + " </div>"; String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(emailContent, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); mp.addBodyPart(backgroundImage); mp.addBodyPart(giftImage); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(mp); message.saveChanges(); Transport.send(message); ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()), md5, 0); referralDAO.insertNewReferral(referral); return true; }
From source file:de.innovationgate.wgpublisher.WGACore.java
public void send(WGAMailNotification notification) { WGAMailConfiguration config = getMailConfig(); if (config != null && config.isEnableAdminNotifications()) { try {//from w ww. ja va 2s.c o m Message msg = new MimeMessage(config.createMailSession()); // set recipient and from address String toAddress = config.getToAddress(); if (toAddress == null) { getLog().error( "Unable to send wga admin notification because no recipient address is configured"); return; } msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); InternetAddress[] fromAddr = new InternetAddress[1]; fromAddr[0] = new InternetAddress(config.getFromAddress()); msg.addFrom(fromAddr); msg.setSentDate(new Date()); InetAddress localMachine = InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); String serverName = getWgaConfiguration().getServerName(); if (serverName == null) { serverName = hostname; } msg.setSubject(notification.getSubject()); msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType()); MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); StringBuffer strBody = new StringBuffer(); strBody.append("<html><head></head><body style=\"color:#808080\">"); strBody.append(notification.getMessage()); String rootURL = getWgaConfiguration().getRootURL(); if (rootURL != null) { //strBody.append("<br><br>"); strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName() + " admin client ...</a></p>"); } // append footer strBody.append("<br><br><b>System information:</b><br><br>"); strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>"); strBody.append("<b>Host:</b> " + hostname + "<br>"); strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>"); strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ")"); strBody.append("</body></html>"); body.setText(strBody.toString()); body.setHeader("MIME-Version", "1.0"); body.setHeader("Content-Type", "text/html"); content.addBodyPart(body); AppLog appLog = WGA.get(this).service(AppLog.class); if (notification.isAttachLogfile()) { MimeBodyPart attachmentBody = new MimeBodyPart(); StringWriter applog = new StringWriter(); int applogSize = appLog.getLinesCount(); int offset = applogSize - notification.getLogfileLines(); if (offset < 0) { offset = 1; } appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false); attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain")); attachmentBody.setFileName("wga.log"); content.addBodyPart(attachmentBody); } msg.setContent(content); // Send mail Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender"); mailThread.start(); } catch (Exception e) { getLog().error("Unable to send wga admin notification.", e); } } }
From source file:net.wastl.webmail.plugins.SendMessage.java
public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException, ServletException { if (sess1 == null) { throw new WebMailException( "No session was given. If you feel this is incorrect, please contact your system administrator"); }/*from ww w . ja v a 2 s .com*/ WebMailSession session = (WebMailSession) sess1; UserData user = session.getUser(); HTMLDocument content; Locale locale = user.getPreferredLocale(); /* Save message in case there is an error */ session.storeMessage(head); if (head.isContentSet("SEND")) { /* The form was submitted, now we will send it ... */ try { MimeMessage msg = new MimeMessage(mailsession); Address from[] = new Address[1]; try { /** * Why we need * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()? * * Because we specify client browser's encoding to UTF-8, IE seems * to send all data encoded in UTF-8. We have to transcode all byte * sequences we received to UTF-8, and next we encode those strings * using MimeUtility.encodeText() depending on user's locale. Since * MimeUtility.encodeText() is used to convert the strings into its * transmission format, finally we can use the strings in the * outgoing e-mail which relies on receiver's email agent to decode * the strings. * * As described in JavaMail document, MimeUtility.encodeText() conforms * to RFC2047 and as a result, we'll get strings like "=?Big5?B......". */ /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()), // MimeUtility.encodeText(session.getUser().getFullName())); from[0] = new InternetAddress( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale), TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null, locale)); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName()); } StringTokenizer t; try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("TO").trim(), ",;"); } /* Check To: field, when empty, throw an exception */ if (t.countTokens() < 1) { throw new MessagingException("The recipient field must not be empty!"); } Address to[] = new Address[t.countTokens()]; int i = 0; while (t.hasMoreTokens()) { to[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("CC").trim(), ",;"); } Address cc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { cc[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("BCC").trim(), ",;"); } Address bcc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { bcc[i] = new InternetAddress(t.nextToken().trim()); i++; } session.setSent(false); msg.addFrom(from); if (to.length > 0) { msg.addRecipients(Message.RecipientType.TO, to); } if (cc.length > 0) { msg.addRecipients(Message.RecipientType.CC, cc); } if (bcc.length > 0) { msg.addRecipients(Message.RecipientType.BCC, bcc); } msg.addHeader("X-Mailer", WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion()); String subject = null; if (!head.isContentSet("SUBJECT")) { subject = "no subject"; } else { try { // subject=MimeUtility.encodeText(head.getContent("SUBJECT")); subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1", locale); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); subject = head.getContent("SUBJECT"); } } msg.addHeader("Subject", subject); if (head.isContentSet("REPLY-TO")) { // msg.addHeader("Reply-To",head.getContent("REPLY-TO")); msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"), "ISO8859_1", locale)); } msg.setSentDate(new Date(System.currentTimeMillis())); String contnt = head.getContent("BODY"); //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); String charset = "utf-8"; MimeMultipart cont = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); // Transcode to UTF-8 contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8"); // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { txt.setText(contnt, "Big5"); txt.setHeader("Content-Type", "text/plain; charset=\"Big5\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } else { txt.setText(contnt, "utf-8"); txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } /* Add an advertisement if the administrator requested to do so */ cont.addBodyPart(txt); if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) { MimeBodyPart adv = new MimeBodyPart(); String file = ""; if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) { file = store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } else { file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator") + store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } String advcont = ""; try { BufferedReader fin = new BufferedReader(new FileReader(file)); String line = fin.readLine(); while (line != null && !line.equals("")) { advcont += line + "\n"; line = fin.readLine(); } fin.close(); } catch (IOException ex) { } /** * Transcode to UTF-8; Since advcont comes from file, we transcode * it from default encoding. */ // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { advcont = new String(advcont.getBytes(), "Big5"); adv.setText(advcont, "Big5"); adv.setHeader("Content-Type", "text/plain; charset=\"Big5\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } else { advcont = new String(advcont.getBytes(), "UTF-8"); adv.setText(advcont, "utf-8"); adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } cont.addBodyPart(adv); } for (String attachmentKey : session.getAttachments().keySet()) { ByteStore bs = session.getAttachment(attachmentKey); InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Transfer-Encoding", "BASE64"); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); /* This is used to write to the Pipe asynchronously to avoid blocking */ StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000); BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64")); encoder.write(bs.getBytes()); encoder.flush(); encoder.close(); //MimeBodyPart att1=sconn.getResult(); MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes()); if (bs.getDescription() != "") { att1.setDescription(bs.getDescription(), "utf-8"); } /** * As described in FileAttacher.java line #95, now we need to * encode the attachment file name. */ // att1.setFileName(bs.getName()); String fileName = bs.getName(); String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry()); String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null); if (encodedFileName.equals(fileName)) { att1.addHeader("Content-Type", bs.getContentType()); att1.setFileName(fileName); } else { att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset); encodedFileName = encodedFileName.substring(localeCharset.length() + 5, encodedFileName.length() - 2); encodedFileName = encodedFileName.replace('=', '%'); att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''" + encodedFileName); } cont.addBodyPart(att1); } msg.setContent(cont); // } msg.saveChanges(); boolean savesuccess = true; msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid")); if (session.getUser().wantsSaveSent()) { String folderhash = session.getUser().getSentFolder(); try { Folder folder = session.getFolder(folderhash); Message[] m = new Message[1]; m[0] = msg; folder.appendMessages(m); } catch (MessagingException e) { savesuccess = false; } catch (NullPointerException e) { // Invalid folder: savesuccess = false; } } boolean sendsuccess = false; try { Transport.send(msg); Address sent[] = new Address[to.length + cc.length + bcc.length]; int c1 = 0; int c2 = 0; for (c1 = 0; c1 < to.length; c1++) { sent[c1] = to[c1]; } for (c2 = 0; c2 < cc.length; c2++) { sent[c1 + c2] = cc[c2]; } for (int c3 = 0; c3 < bcc.length; c3++) { sent[c1 + c2 + c3] = bcc[c3]; } sendsuccess = true; throw new SendFailedException("success", new Exception("success"), sent, null, null); } catch (SendFailedException e) { session.handleTransportException(e); } //session.clearMessage(); content = new XHTMLDocument(session.getModel(), store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme())); // if(sendsuccess) session.clearWork(); } catch (Exception e) { log.error("Could not send messsage", e); throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")"); } } else if (head.isContentSet("ATTACH")) { /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to have two targets without Javascript) */ content = parent.getURLHandler().handleURL("/compose/attach", session, head); } else { throw new DocumentNotFoundException("Could not send message. (Reason: No content given)"); } return content; }
From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java
@Override public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) { return new AbstractMailSendBuilder() { @Override//from w w w . jav a2 s .co m public void send(final String content) throws Exception { __sendExecPool.execute(new Runnable() { @Override public void run() { try { MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed()); // for (String _to : getTo()) { _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to)); } for (String _cc : getCc()) { _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc)); } for (String _bcc : getBcc()) { _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc)); } // if (getLevel() != null) { switch (getLevel()) { case LEVEL_HIGH: _message.setHeader("X-MSMail-Priority", "High"); _message.setHeader("X-Priority", "1"); break; case LEVEL_NORMAL: _message.setHeader("X-MSMail-Priority", "Normal"); _message.setHeader("X-Priority", "3"); break; case LEVEL_LOW: _message.setHeader("X-MSMail-Priority", "Low"); _message.setHeader("X-Priority", "5"); break; default: } } // String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8"); _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(), serverCfgMeta.getDisplayName(), _charset)); _message.setSubject(getSubject(), _charset); // Multipart _container = new MimeMultipart(); // MimeBodyPart _textBodyPart = new MimeBodyPart(); if (getMimeType() == null) { mimeType(IMailSender.MimeType.TEXT_PLAIN); } _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset); _container.addBodyPart(_textBodyPart); // ??<img src="cid:<CID_NAME>"> for (PairObject<String, File> _file : getAttachments()) { if (_file.getValue() != null) { MimeBodyPart _fileBodyPart = new MimeBodyPart(); FileDataSource _fileDS = new FileDataSource(_file.getValue()); _fileBodyPart.setDataHandler(new DataHandler(_fileDS)); if (_file.getKey() != null) { _fileBodyPart.setHeader("Content-ID", _file.getKey()); } _fileBodyPart.setFileName(_fileDS.getName()); _container.addBodyPart(_fileBodyPart); } } // ?? _message.setContent(_container); Transport.send(_message); } catch (Exception e) { throw new RuntimeException(RuntimeUtils.unwrapThrow(e)); } } }); } }; }