List of usage examples for javax.mail.internet MimeBodyPart setText
@Override public void setText(String text, String charset, String subtype) throws MessagingException
From source file:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java
public MimeMessage send(final @NonNull Email email, final @NonNull String template, final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures) throws CannotSendEmailException { email.setSentAt(new Date()); final MimeMessage mimeMessage = toMimeMessage(email); try {/*from w ww . j av a2 s.c o m*/ final MimeMultipart content = new MimeMultipart("related"); String text = templateService.mergeTemplateIntoString(template, fromNullable(modelObject).or(ImmutableMap.of())); for (final InlinePicture inlinePicture : inlinePictures) { final String cid = UUID.randomUUID().toString(); //Set the cid in the template text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid); //Set the image part final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(inlinePicture.getFile()); imagePart.setContentID('<' + cid + '>'); imagePart.setDisposition(MimeBodyPart.INLINE); imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType()); content.addBodyPart(imagePart); } //Set the HTML text part final MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(text, email.getEncoding().displayName(), "html"); content.addBodyPart(textPart); mimeMessage.setContent(content); javaMailSender.send(mimeMessage); } catch (IOException e) { log.error("The template file cannot be read", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the template file", e); } catch (TemplateException e) { log.error("The template file cannot be processed", e); throw new CannotSendEmailException( "Error while processing the template file with the given model object", e); } catch (MessagingException e) { log.error("The mime message cannot be created", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the mime content", e); } return mimeMessage; }
From source file:at.molindo.notify.channel.mail.AbstractMailClient.java
@Override public synchronized void send(Dispatch dispatch) throws MailException { Message message = dispatch.getMessage(); String recipient = dispatch.getParams().get(MailChannel.RECIPIENT); String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME); String subject = message.getSubject(); try {/*from ww w . ja v a 2s . c o m*/ MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) { @Override protected void updateMessageID() throws MessagingException { String domain = _from.getAddress(); int idx = _from.getAddress().indexOf('@'); if (idx >= 0) { domain = domain.substring(idx + 1); } setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">"); } }; mm.setFrom(_from); mm.setSender(_from); InternetAddress replyTo = getReplyTo(); if (replyTo != null) { mm.setReplyTo(new Address[] { replyTo }); } mm.setHeader("X-Mailer", "molindo-notify"); mm.setSentDate(new Date()); mm.setRecipient(RecipientType.TO, new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName())); mm.setSubject(subject, CharsetUtils.UTF_8.displayName()); if (_format == Format.HTML) { if (message.getType() == Type.TEXT) { throw new MailException("can't send HTML mail from TEXT message", false); } mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) { mm.setText(message.getText(), CharsetUtils.UTF_8.displayName()); } else if (_format == Format.MULTI) { MimeBodyPart html = new MimeBodyPart(); html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); MimeBodyPart text = new MimeBodyPart(); text.setText(message.getText(), CharsetUtils.UTF_8.displayName()); /* * The formats are ordered by how faithful they are to the * original, with the least faithful first and the most faithful * last. (http://en.wikipedia.org/wiki/MIME#Alternative) */ MimeMultipart mmp = new MimeMultipart(); mmp.setSubType("alternative"); mmp.addBodyPart(text); mmp.addBodyPart(html); mm.setContent(mmp); } else { throw new NotifyRuntimeException( "unexpected format (" + _format + ") or type (" + message.getType() + ")"); } send(mm); } catch (final MessagingException e) { throw new MailException( "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e, isTemporary(e)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("utf8 unknown?", e); } }
From source file:com.cosmicpush.plugins.smtp.EmailMessage.java
/** * @param session the applications current session. * @throws EmailMessageException in response to any other type of exception. *//*from www. ja v a2s . c om*/ @SuppressWarnings({ "ConstantConditions" }) protected void send(Session session) throws EmailMessageException { try { // create a message MimeMessage msg = new MimeMessage(session); //set some of the basic attributes. msg.setFrom(fromAddress); msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses)); msg.setSubject(subject); msg.setSentDate(new Date()); if (replyToAddress.isEmpty() == false) { msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress)); } // create the Multipart and add set it as the content of the message Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // create and fill the HTML part of the messgae if it exists if (html != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(html, "UTF-8", "html"); multipart.addBodyPart(bodyPart); } // create and fill the text part of the messgae if it exists if (text != null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text, "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } if (html == null && text == null) { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("", "UTF-8", "plain"); multipart.addBodyPart(bodyPart); } // remove any nulls from the list of attachments. while (attachments.remove(null)) { /* keep going */ } // Attach any files that we have, making sure that they exist first for (File file : attachments) { if (file.exists() == false) { throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist."); } else { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(file); multipart.addBodyPart(attachmentPart); } } // send the message Transport.send(msg); } catch (EmailMessageException ex) { throw ex; } catch (Exception ex) { throw new EmailMessageException("Exception sending email\n" + toString(), ex); } }
From source file:Implement.Service.AdminServiceImpl.java
@Override public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException { String path = System.getProperty("catalina.base"); MimeBodyPart logo = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png")); logo.setDataHandler(new DataHandler(source)); logo.setFileName("logoIcon.png"); logo.setDisposition(MimeBodyPart.INLINE); logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid MimeBodyPart facebook = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png")); facebook.setDataHandler(new DataHandler(source)); facebook.setFileName("facebookIcon.png"); facebook.setDisposition(MimeBodyPart.INLINE); facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid MimeBodyPart twitter = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png")); twitter.setDataHandler(new DataHandler(source)); twitter.setFileName("twitterIcon.png"); twitter.setDisposition(MimeBodyPart.INLINE); twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid MimeBodyPart insta = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png")); insta.setDataHandler(new DataHandler(source)); insta.setFileName("instaIcon.png"); insta.setDisposition(MimeBodyPart.INLINE); insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid MimeBodyPart youtube = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png")); youtube.setDataHandler(new DataHandler(source)); youtube.setFileName("youtubeIcon.png"); youtube.setDisposition(MimeBodyPart.INLINE); youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid MimeBodyPart pinterest = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png")); pinterest.setDataHandler(new DataHandler(source)); pinterest.setFileName("pinterestIcon.png"); pinterest.setDisposition(MimeBodyPart.INLINE); pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid String content = "<div style=' width: 507px;background-color: #f2f2f4;'>" + " <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>" + " <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>" + " <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + " </div>" + " <div style=' padding: 50px;margin-bottom: 20px;'>" + " <div id='email-form'>" + " <div style='margin-bottom: 20px'>" + " Hi " + emailData.getLastName() + " ,<br/>" + " Your package " + emailData.getLastestPackageName() + " has been approved" + " </div>" + " <div style='margin-bottom: 20px'>" + " Thanks,<br/>" + " Youtripper team\n" + " </div>" + " </div>" + " <div style='border-top: solid 1px #c4c5cc;text-align:center;'>" + " <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>" + " <div>" + " <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>" + " <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>" + " <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>" + " <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>" + " <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>" + " </div>" + " <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon," + " <br>Pravet, Bangkok, Thailand 10250</p>" + " </div>" + " </div>" + "</div>"; MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1);/*from w w w . j a va2 s . co m*/ mp.addBodyPart(logo); mp.addBodyPart(facebook); mp.addBodyPart(twitter); mp.addBodyPart(insta); mp.addBodyPart(youtube); mp.addBodyPart(pinterest); final String username = "noreply@youtripper.com"; final String password = "Tripper190515"; 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); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("noreply@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail())); message.setSubject("Package Approved!"); message.setContent(mp); message.saveChanges(); Transport.send(message); return true; }
From source file:fr.xebia.cloud.cloudinit.CloudInitUserDataBuilder.java
/** * Add given file <code>in</code> to the cloud-init mime message. * //from w ww .j a va2 s.c om * @param fileType * @param in * file to add as readable * @return the builder * @throws IllegalArgumentException * the given <code>fileType</code> was already added to this * cloud-init mime message. */ @Nonnull public CloudInitUserDataBuilder addFile(@Nonnull FileType fileType, @Nonnull Readable in) throws IllegalArgumentException { Preconditions.checkNotNull(fileType, "'fileType' can NOT be null"); Preconditions.checkNotNull(in, "'in' can NOT be null"); Preconditions.checkArgument(!alreadyAddedFileTypes.contains(fileType), "%s as already been added", fileType); alreadyAddedFileTypes.add(fileType); try { StringWriter sw = new StringWriter(); CharStreams.copy(in, sw); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(sw.toString(), charset.name(), fileType.getMimeTextSubType()); mimeBodyPart.setFileName(fileType.getFileName()); userDataMultipart.addBodyPart(mimeBodyPart); } catch (IOException e) { throw Throwables.propagate(e); } catch (MessagingException e) { throw Throwables.propagate(e); } return this; }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeBodyPart????text/html//ww w . j a v a 2 s . c o m * * @return MimeBodyParttext/html? * @throws MessagingException */ private MimeBodyPart createHtmlPart() throws MessagingException { MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setText(html, charset, "html"); setHeaderToPart(htmlPart); return htmlPart; }
From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java
@Override public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body, List<NodeRef> attachments, boolean html) throws Exception { EmailConfig config = getConfig();//from ww w .j a v a 2 s . com EmailProvider provider = getEmailProvider(config.getProviderId()); Properties props = System.getProperties(); String prefix = "mail." + provider.getOutgoingProto() + "."; props.put(prefix + "host", provider.getOutgoingServer()); props.put(prefix + "port", provider.getOutgoingPort()); props.put(prefix + "auth", "true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName())); if (to != null) { InternetAddress[] recipients = new InternetAddress[to.size()]; for (int i = 0; i < to.size(); i++) recipients[i] = new InternetAddress(to.get(i)); msg.setRecipients(Message.RecipientType.TO, recipients); } if (cc != null) { InternetAddress[] recipients = new InternetAddress[cc.size()]; for (int i = 0; i < cc.size(); i++) recipients[i] = new InternetAddress(cc.get(i)); msg.setRecipients(Message.RecipientType.CC, recipients); } if (bcc != null) { InternetAddress[] recipients = new InternetAddress[bcc.size()]; for (int i = 0; i < bcc.size(); i++) recipients[i] = new InternetAddress(bcc.get(i)); msg.setRecipients(Message.RecipientType.BCC, recipients); } msg.setSubject(subject); msg.setHeader("X-Mailer", "Alvex Emailer"); msg.setSentDate(new Date()); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); if (body != null) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body, "utf-8", html ? "html" : "plain"); multipart.addBodyPart(messageBodyPart); } if (attachments != null) for (NodeRef att : attachments) { messageBodyPart = new MimeBodyPart(); String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME); messageBodyPart .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService))); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto()); t.connect(config.getUsername(), config.getPassword()); t.sendMessage(msg, msg.getAllRecipients()); t.close(); }
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 www .j a va2s .c om*/ }); 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); }//from ww w . ja v a 2 s. c o 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:org.alfresco.repo.imap.ContentModelMessage.java
private MimeBodyPart getTextBodyPart(String bodyText, String subtype, String mimeType) throws MessagingException { MimeBodyPart result = new MimeBodyPart(); result.setText(bodyText, AlfrescoImapConst.UTF_8, subtype); result.addHeader(AlfrescoImapConst.CONTENT_TYPE, mimeType + AlfrescoImapConst.CHARSET_UTF8); result.addHeader(AlfrescoImapConst.CONTENT_TRANSFER_ENCODING, AlfrescoImapConst.BASE_64_ENCODING); return result; }