List of usage examples for javax.mail.internet MimeMessage addFrom
@Override public void addFrom(Address[] addresses) throws MessagingException
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>//from w w w . j av a2 s .c o m * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server/* ww w.jav a 2s .c o m*/ * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server// w w w . ja v a 2 s .c o m * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); final Session session = Session.getInstance(props, null); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }/*from w ww. ja v a 2 s . c o m*/ if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getBcc() != null) { message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); textBodyPart.setHeader("Content-Transfer-Encoding", "base64"); textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\""); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64"); htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\""); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:org.xsocket.connection.SimpleSmtpClient.java
public void send(String contentType, String text, String from, String to) throws IOException, MessagingException { MimeMessage msg = new MimeMessage((Session) null); msg.setContent(text, contentType);//w w w . ja v a2 s . c o m msg.addFrom(InternetAddress.parse(from)); msg.addRecipients(RecipientType.TO, InternetAddress.parse(to)); send(msg); }