List of usage examples for javax.mail Multipart addBodyPart
public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java
@Override public Multipart createContent(Site site, String templateFilename, Model context) throws IOException, MessagingException { Template textTemplate = getEmailTemplate(site, "txt", templateFilename); Template htmlTemplate = getEmailTemplate(site, "html", templateFilename); // Create a "text" Multipart message Multipart mp = createPartForMultipart(textTemplate, context, "alternative", ContentType.TEXT_PLAIN); // Create a "HTML" Multipart message Multipart htmlContent = createPartForMultipart(htmlTemplate, context, "related", ContentType.TEXT_HTML); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent);/*from w w w. j av a2 s .c o m*/ mp.addBodyPart(htmlPart); return mp; }
From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java
public MimeMessage getMimeMessage() throws MessagingException { if (attachments.isEmpty()) { switch (messageType) { case HTML: mimeMessage.setContent(messageBody, "text/html; charset=utf-8"); break; case TEXT: mimeMessage.setText(messageBody, "UTF-8"); mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable"); break; }// w w w . j a va2 s. c o m } else { MimeBodyPart mimeBodyPart = new MimeBodyPart(); switch (messageType) { case HTML: mimeBodyPart.setContent(messageBody, "text/html; charset=utf-8"); break; case TEXT: mimeBodyPart.setText(messageBody, "UTF-8"); mimeMessage.addHeader("Content-Transfer-Encoding", "quoted-printable"); break; } mimeBodyPart.setDisposition(Part.INLINE); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); for (BodyPart attachmentPart : attachments) { multipart.addBodyPart(attachmentPart); } mimeMessage.setContent(multipart); } return mimeMessage; }
From source file:net.sf.jclal.util.mail.SenderEmail.java
/** * Send the email with the indicated parameters * * @param subject The subject//ww w . j a va 2 s . c o m * @param content The content * @param reportFile The reportFile to send */ public void sendEmail(String subject, String content, File reportFile) { // Get system properties Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); if (!user.isEmpty() && !pass.isEmpty()) { properties.setProperty("mail.user", user); properties.setProperty("mail.password", pass); } // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, toRecipients.toString()); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText(content); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); if (attachReporFile) { messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile))); messageBodyPart.setFileName(reportFile.getName()); multipart.addBodyPart(messageBodyPart); } // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e); } }
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public void addAttachement(File file) { try {//w w w.ja v a 2 s. c o m /* Check if email has already some contents. */ Object content; try { content = this.source.getContent(); } catch (IOException e) { /* If no content, then content is null.*/ content = null; log.warn("Email content is empty.", e); } if (content != null) { if (content instanceof String) { /* This message is not multipart yet. Change it to multipart. */ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText((String) this.source.getContent()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); this.source.setContent(multipart); } } else { /* No content, then create initial multipart content. */ Multipart multipart = new MimeMultipart(); this.source.setContent(multipart); } /* Get current content. */ Multipart multipart = (Multipart) this.source.getContent(); /* add attachment as a new part. */ MimeBodyPart attachementPart = new MimeBodyPart(); DataSource fileSource = new FileDataSource(file); DataHandler fileDataHandler = new DataHandler(fileSource); attachementPart.setDataHandler(fileDataHandler); attachementPart.setFileName(file.getName()); multipart.addBodyPart(attachementPart); } catch (Exception e) { throw new GmailException("Failed to add attachement", e); } }
From source file:ee.cyber.licensing.service.MailService.java
public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId) throws MessagingException, IOException, SQLException { License license = licenseRepository.findById(licenseId); List<Contact> contacts = contactRepository.findAll(license.getCustomer()); List<String> receivers = getReceivers(mailbody, contacts); logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }//from w ww . j a va 2 s . c o m }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "License dude")); //mailMessage.setReplyTo(InternetAddress.parse(email, false)); mailMessage.setSubject(mailbody.getSubject()); //String emailBody = body + "<br><br> Regards, <br>Cybernetica team"; mailMessage.setSentDate(new Date()); for (String receiver : receivers) { mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); } if (fileId != 0) { MailAttachment file = fileRepository.findById(fileId); if (file != null) { String fileName = file.getFileName(); byte[] fileData = file.getData_b(); if (fileName != null) { // Create a multipart message for attachment Multipart multipart = new MimeMultipart(); // Body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(mailbody.getBody(), "text/html"); multipart.addBodyPart(messageBodyPart); //Attachment part messageBodyPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); mailMessage.setContent(multipart); } } } else { mailMessage.setContent(mailbody.getBody(), "text/html"); } logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java
@Override public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text, final Message previousMailMessage) { LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)"); if (suppressMail) { return;/* w ww . ja v a 2 s .c om*/ } setMailProperties(); MimeMessagePreparator messagePreparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) { setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses()); } if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) { setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses()); } if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) { setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses()); } if (null != mailMetaData.getFromAddress()) { mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName()) .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress()) .append(MailConstants.GREATER_SYMBOL).toString())); } if (null != mailMetaData.getSubject() && null != text) { mimeMessage.setSubject(mailMetaData.getSubject()); } if (null != text) { mimeMessage.setText(text); } // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE)); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(previousMailMessage.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message mimeMessage.setContent(multipart); } }; try { mailSender.send(messagePreparator); } catch (MailException mailException) { LOGGER.error("Error while sending mail to configured mail account", mailException); throw new SendMailException( EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException); } LOGGER.info("mail sent successfully"); }
From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java
private MimeMessage buildMessage(MimeMessage source, PartsContext context) throws MessagingException, IOException { List<Part> parts = context.getParts(); assert (parts.size() > 0); MimeMessage newMessage;/*w ww .j a v a 2 s.co m*/ if (parts.size() > 1) { /* there is more than one S/MIME part so we need to create a multipart message */ Multipart mp = new MimeMultipart(); for (Part part : parts) { MimeBodyPart bodyPart = BodyPartUtils.toMimeBodyPart(part); mp.addBodyPart(bodyPart); } newMessage = new MimeMessage(MailSession.getDefaultSession()); newMessage.setContent(mp); } else { newMessage = BodyPartUtils.toMessage(parts.get(0), true /* clone */); } copyNonContentHeaders(source, newMessage); return newMessage; }
From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java
@Override public void sendInvite(final String subject, final String description, final Participant from, final List<Participant> attendees, final Date startDate, final Date endDate, final String location) throws Exception { this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port")); this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.properties.put("mail.smtp.socketFactory.fallback", "false"); validate();//ww w. j a v a 2 s . co m LOG.info("Sending meeting invite"); LOG.debug("Mail Properties :: " + this.properties); Session session; if (password != null) { session = Session.getInstance(this.properties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { session = Session.getInstance(this.properties); } ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location); cal.init(); StringBuffer sb = new StringBuffer(); sb.append(from.getEmail()); for (Participant bean : attendees) { if (sb.length() > 0) { sb.append(","); } sb.append(bean.getEmail()); } MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from.getEmail())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString())); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart iCal = new MimeBodyPart(); iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); LOG.debug("Calender Request :: \n" + cal.toString()); multipart.addBodyPart(iCal); message.setContent(multipart); Transport.send(message); }
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); mp.addBodyPart(logo);// w w w . ja v a2 s. co m 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:com.tdclighthouse.commons.mail.util.MailClient.java
public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException { // a brief validation if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) { throw new IllegalArgumentException(); }//www . ja v a 2 s. c om Session session = getSession(); // Define a new mail message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (int i = 0; i < to.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } message.setSubject(mail.getSubject(), "utf-8"); // use a MimeMultipart as we need to handle the file attachments Multipart multipart = new MimeMultipart("alternative"); if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) { // add the message body to the mime message BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain" multipart.addBodyPart(textPart); } if (mail.getHtmlBody() != null) { BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8"); multipart.addBodyPart(pixPart); } // add any file attachments to the message addAtachments(mail.getAttachments(), multipart); // Put all message parts in the message message.setContent(multipart); // Send the message Transport.send(message); }