List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java
public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException { // get information about the original message. Address[] originalFromRecipient = message.getFrom(); Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO); Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC); Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC); String originalSubject = message.getSubject(); // create the html for the string buffer. StringBuffer html = new StringBuffer(); html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>"); html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>"); // iterate over the addresses. if (originalFromRecipient != null) { for (int i = 0; i < originalFromRecipient.length; i++) { html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>"); }//from w w w . j a va2 s .c om } if (originalToRecipient != null) { for (int i = 0; i < originalToRecipient.length; i++) { html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>"); } } if (originalCcRecipient != null) { for (int i = 0; i < originalCcRecipient.length; i++) { html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>"); } } if (originalBccRecipient != null) { for (int i = 0; i < originalBccRecipient.length; i++) { html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>"); } } html.append("</table></body></html>"); MimeBodyPart sentToBodyPart = new MimeBodyPart(); sentToBodyPart.setContent(html.toString(), "text/html"); sentToBodyPart.setHeader("Content-ID", "original-addresses"); sentToBodyPart.setDisposition("inline"); return sentToBodyPart; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from w w w .ja v a2 s .com * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:com.zacwolf.commons.email.Email.java
public Multipart getAsMultipart() throws MessagingException { /** First we create the "related" htmlmultipart for the html email content: * ?//from w ww. jav a 2 s . com * msg.setContent() * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [BodyPart] * * * **/ final Multipart htmlmultipart = new MimeMultipart("related"); final BodyPart htmlmessageBodyPart = new MimeBodyPart(); htmlmultipart.addBodyPart(htmlmessageBodyPart); final org.jsoup.nodes.Document doc = Jsoup.parse(getBody(), "UTF-8"); prepareImgs(doc, htmlmultipart); prepare(doc); htmlmessageBodyPart.setContent(doc.toString(), "text/html; charset=utf-8"); // populate the top multipart Multipart msgmultipart = htmlmultipart; if (getBodyPlainText() != null) {// Now create a plain-text body part /** * If there is a plain text attachment (and their should always be one), * then an "alternative" type MimeMultipart is added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * */ msgmultipart = new MimeMultipart("alternative"); final BodyPart plaintxtBodyPart = new MimeBodyPart(); plaintxtBodyPart.setText(getBodyPlainText()); final BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(htmlmultipart); msgmultipart.addBodyPart(plaintxtBodyPart); msgmultipart.addBodyPart(htmlBodyPart); } /** * If there are non-inline attachments, then a "mixed" type * MimeMultipart object has to be added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("mixed")] * ? * wrap [MimeBodyPart] * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * * EmailAttachment (non-inline) [MimeBodyPart] * * EmailAttachment (non-inline) [MimeBodyPart] * * * */ Multipart mixed = msgmultipart; final Set<EmailAttachment> noninlineattachments = new HashSet<EmailAttachment>(); for (EmailAttachment attach : getAttachments().values()) if (attach.disposition != null && !attach.disposition.equals(MimeBodyPart.INLINE)) noninlineattachments.add(attach); // If there are non-IN-LINE attachments, we'll have to create another layer "mixed" MultiPart object if (!noninlineattachments.isEmpty()) { mixed = new MimeMultipart("mixed"); //Multiparts are not themselves containers, so create a wrapper BodyPart container final BodyPart wrap = new MimeBodyPart(); wrap.setContent(msgmultipart); mixed.addBodyPart(wrap); for (EmailAttachment attach : noninlineattachments) mixed.addBodyPart(attach); } return mixed; }
From source file:mitm.common.mail.MailUtilsTest.java
@Test public void testUnknownContentTypeMultipartAddPart() throws IOException, MessagingException { MimeMessage message = loadMessage("unknown-content-type-multipart.eml"); MimeMultipart multipart = (MimeMultipart) message.getContent(); BodyPart newPart = new MimeBodyPart(); newPart.setContent("new part", "text/plain"); multipart.addBodyPart(newPart);/* ww w. j av a2 s.c o m*/ message.saveChanges(); MailUtils.validateMessage(message); File file = new File("test/tmp/testunknowncontenttypemultipartaddpart.eml"); MailUtils.writeMessage(message, file); }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
/** * Attaches a file as a body part to the multipart message * * @param multipart/*from w w w . j a va 2 s.c o m*/ * @param attachment * @throws MessagingException */ private void addPart(Multipart multipart, Message msg) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); part.setContent(msg.getBody(), msg.getType()); multipart.addBodyPart(part); }
From source file:eagle.common.email.EagleMailClient.java
public boolean send(String from, String to, String cc, String title, String templatePath, VelocityContext context, Map<String, File> attachments) { if (attachments == null || attachments.isEmpty()) { return send(from, to, cc, title, templatePath, context); }//from w ww . j a v a 2 s . co m Template t = null; List<MimeBodyPart> mimeBodyParts = new ArrayList<MimeBodyPart>(); Map<String, String> cid = new HashMap<String, String>(); for (Map.Entry<String, File> entry : attachments.entrySet()) { final String attachment = entry.getKey(); final File attachmentFile = entry.getValue(); final MimeBodyPart mimeBodyPart = new MimeBodyPart(); if (attachmentFile != null && attachmentFile.exists()) { DataSource source = new FileDataSource(attachmentFile); try { mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(attachment); mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); mimeBodyPart.setContentID(attachment); cid.put(attachment, mimeBodyPart.getContentID()); mimeBodyParts.add(mimeBodyPart); } catch (MessagingException e) { LOG.error("Generate mail failed, got exception while attaching files: " + e.getMessage(), e); } } else { LOG.error("Attachment: " + attachment + " is null or not exists"); } } //TODO remove cid, because not used at all if (LOG.isDebugEnabled()) LOG.debug("Cid maps: " + cid); context.put("cid", cid); try { t = velocityEngine.getTemplate(BASE_PATH + templatePath); } catch (ResourceNotFoundException ex) { // LOGGER.error("Template not found:"+BASE_PATH + templatePath, ex); } if (t == null) { try { t = velocityEngine.getTemplate(templatePath); } catch (ResourceNotFoundException e) { try { t = velocityEngine.getTemplate("/" + templatePath); } catch (Exception ex) { LOG.error("Template not found:" + "/" + templatePath, ex); } } } final StringWriter writer = new StringWriter(); t.merge(context, writer); if (LOG.isDebugEnabled()) LOG.debug(writer.toString()); return this._send(from, to, cc, title, writer.toString(), mimeBodyParts); }
From source file:rescustomerservices.GmailQuickstart.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.//from ww w . j a v a 2 s . c o m * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:bean.RedSocial.java
/** * /*from w w w . j av a 2 s .c o m*/ * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);/*from w w w .ja va2 s . com*/ multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:org.apache.lens.server.query.QueryEndNotifier.java
/** Send mail. * * @param host the host * @param port the port * @param email the email * @param mailSmtpTimeout the mail smtp timeout * @param mailSmtpConnectionTimeout the mail smtp connection timeout */ public static void sendMail(String host, String port, Email email, int mailSmtpTimeout, int mailSmtpConnectionTimeout) throws Exception { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(email.getFrom())); for (String recipient : email.getTo().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); }// www . j a v a 2 s . c o m if (email.getCc() != null && email.getCc().length() > 0) { for (String recipient : email.getCc().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient)); } } message.setSubject(email.getSubject()); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(email.getMessage()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); }