List of usage examples for javax.mail.internet MimeMessage setSubject
public void setSubject(String subject, String charset) throws MessagingException
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;//from w w w . jav a 2s . c o m String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject + "' and the body " + body); try { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Create basic Message which contains all headers. No body is filled * * @param session the Session//from w w w .j av a 2 s .co m * @param action the action * @return message * @throws AddressException * @throws MessagingException */ public Message createMessage(Session session, SendMessageAction action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SmtpMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSentDate(new Date()); message.addHeader("User-Agent:", "HUPA, The Apache JAMES webmail client."); message.addHeader("X-Originating-IP", getClientIpAddr()); message.setSubject(m.getSubject(), "utf-8"); updateHeaders(message, action); message.saveChanges(); return message; }
From source file:org.mule.transport.email.transformers.StringToEmailMessage.java
@Override public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException { String endpointAddress = endpoint.getEndpointURI().getAddress(); SmtpConnector connector = (SmtpConnector) endpoint.getConnector(); String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress); String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses()); String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses()); String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress()); String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY, connector.getReplyToAddresses()); String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject()); String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY, connector.getContentType()); Properties headers = new Properties(); Properties customHeaders = connector.getCustomHeaders(); if (customHeaders != null && !customHeaders.isEmpty()) { headers.putAll(customHeaders);/*w w w. j a va2s . c o m*/ } Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY); if (otherHeaders != null && !otherHeaders.isEmpty()) { //TODO Whats going on here? // final MuleContext mc = context.getMuleContext(); // for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();) // { // String propertyKey = (String) iterator.next(); // mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc); // } headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() { public Object match(String token) { return muleContext.getRegistry().lookupObject(token); } }, otherHeaders)); } if (logger.isDebugEnabled()) { StringBuffer buf = new StringBuffer(); buf.append("Constructing email using:\n"); buf.append("To: ").append(to); buf.append(", From: ").append(from); buf.append(", CC: ").append(cc); buf.append(", BCC: ").append(bcc); buf.append(", Subject: ").append(subject); buf.append(", ReplyTo: ").append(replyTo); buf.append(", Content type: ").append(contentType); buf.append(", Payload type: ").append(message.getPayload().getClass().getName()); buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false)); logger.debug(buf.toString()); } try { MimeMessage email = new MimeMessage( ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession()); email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to)); // sent date email.setSentDate(Calendar.getInstance().getTime()); if (StringUtils.isNotBlank(from)) { email.setFrom(MailUtils.stringToInternetAddresses(from)[0]); } if (StringUtils.isNotBlank(cc)) { email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc)); } if (StringUtils.isNotBlank(bcc)) { email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc)); } if (StringUtils.isNotBlank(replyTo)) { email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo)); } email.setSubject(subject, outputEncoding); for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); email.setHeader(entry.getKey().toString(), entry.getValue().toString()); } setContent(message.getPayload(), email, contentType, message); return email; } catch (Exception e) { throw new TransformerException(this, e); } }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public void sendMail(String host, String from, String to, String subject, String messageText) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); try {/*from www .ja v a 2s .c om*/ MimeMessage msg = new MimeMessage(session); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; try { msg.setFrom(new InternetAddress(from, charset)); for (int i = 0; i < recipients.length; i++) { recipients[i] = new InternetAddress(recipientStrings[i], "", charset); } } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(messageText, charset); Transport.send(msg, recipients); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }
From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java
protected void generateMail(String destination, String copy, String title, String content) throws NamingException, MessagingException { InitialContext ic = new InitialContext(); Session session = (Session) ic.lookup(getJavaMailJndiName()); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false)); if (!isBlank(copy)) { msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false)); }/*from ww w. j ava 2s.c o m*/ msg.setSubject(title, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content, "text/html; charset=utf-8"); Transport.send(msg); }
From source file:org.apache.camel.component.mail.MailBinding.java
/** * Appends the Mail headers from the Camel {@link MailMessage} *//*from www.j av a 2 s . c om*/ protected void appendHeadersFromCamelMessage(MimeMessage mimeMessage, MailConfiguration configuration, Exchange exchange) throws MessagingException { for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) { String headerName = entry.getKey(); Object headerValue = entry.getValue(); if (headerValue != null) { if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(headerName, headerValue, exchange)) { if (headerName.equalsIgnoreCase("subject")) { mimeMessage.setSubject(asString(exchange, headerValue), IOConverter.getCharsetName(exchange, false)); continue; } if (isRecipientHeader(headerName)) { // skip any recipients as they are handled specially continue; } // alternative body should also be skipped if (headerName.equalsIgnoreCase(configuration.getAlternativeBodyHeader())) { // skip alternative body continue; } // Mail messages can repeat the same header... if (ObjectConverter.isCollection(headerValue)) { Iterator iter = ObjectHelper.createIterator(headerValue); while (iter.hasNext()) { Object value = iter.next(); mimeMessage.addHeader(headerName, asString(exchange, value)); } } else { mimeMessage.setHeader(headerName, asString(exchange, headerValue)); } } } } }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *//* w ww.j ava 2 s. co m*/ public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
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 {/*ww w .j av a2 s .co 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:org.pentaho.platform.scheduler2.email.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*from ww w. j a v a 2 s . co m*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail * /* ww w .j av a 2 s.c o m*/ * @param mail The original Mail object * @param session Mail session * @return The MIME message */ private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException { // this will also check for email error InternetAddress from = new InternetAddress(mail.getFrom()); String recipients = mail.getHeader("To"); if (StringUtils.isBlank(recipients)) { recipients = mail.getTo(); } else { recipients = mail.getTo() + "," + recipients; } InternetAddress[] to = toInternetAddresses(recipients); recipients = mail.getHeader("Cc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getCc(); } else { recipients = mail.getCc() + "," + recipients; } InternetAddress[] cc = toInternetAddresses(recipients); recipients = mail.getHeader("Bcc"); if (StringUtils.isBlank(recipients)) { recipients = mail.getBcc(); } else { recipients = mail.getBcc() + "," + recipients; } InternetAddress[] bcc = toInternetAddresses(recipients); if ((to == null) && (cc == null) && (bcc == null)) { LOGGER.info("No recipient -> skipping this email"); return null; } MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setFrom(from); if (to != null) { message.setRecipients(javax.mail.Message.RecipientType.TO, to); } if (cc != null) { message.setRecipients(javax.mail.Message.RecipientType.CC, cc); } if (bcc != null) { message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc); } message.setSubject(mail.getSubject(), EMAIL_ENCODING); for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) { message.setHeader(header.getKey(), header.getValue()); } if (mail.getHtmlPart() != null || mail.getAttachments() != null) { Multipart multipart = createMimeMultipart(mail, context); message.setContent(multipart); } else { message.setText(mail.getTextPart()); } message.setSentDate(new Date()); message.saveChanges(); return message; }