List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Object o, String type) throws MessagingException
From source file:edu.cornell.mannlib.vitro.webapp.email.FreemarkerEmailMessage.java
public boolean send() { try {/*from w ww . j a v a 2s.c o m*/ MimeMessage msg = new MimeMessage(mailSession); msg.setReplyTo(new Address[] { replyToAddress }); if (fromAddress == null) { msg.addFrom(new Address[] { replyToAddress }); } else { msg.addFrom(new Address[] { fromAddress }); } for (Recipient recipient : recipients) { msg.addRecipient(recipient.type, recipient.address); } msg.setSubject(subject); if (textContent.isEmpty()) { if (htmlContent.isEmpty()) { log.error("Message has neither text body nor HTML body"); } else { msg.setContent(htmlContent, "text/html"); } } else { if (htmlContent.isEmpty()) { msg.setContent(textContent, "text/plain"); } else { MimeMultipart content = new MimeMultipart("alternative"); addBodyPart(content, textContent, "text/plain"); addBodyPart(content, htmlContent, "text/html"); msg.setContent(content); } } msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (MessagingException e) { log.error("Failed to send message.", e); return false; } }
From source file:org.latticesoft.util.resource.MessageUtil.java
/** * Sends the email.//from www.j ava 2 s .co m * @param info the EmailInfo containing the message and other details * @param p the properties to set in the environment when instantiating the session * @param auth the authenticator */ public static void sendMail(EmailInfo info, Properties p, Authenticator auth) { try { if (p == null) { if (log.isErrorEnabled()) { log.error("Null properties!"); } return; } Session session = Session.getInstance(p, auth); session.setDebug(true); if (log.isInfoEnabled()) { log.info(p); log.info(session); } MimeMessage mimeMessage = new MimeMessage(session); if (log.isInfoEnabled()) { log.info(mimeMessage); log.info(info.getFromAddress()); } mimeMessage.setFrom(info.getFromAddress()); mimeMessage.setSentDate(new Date()); List l = info.getToList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); if (log.isInfoEnabled()) { log.info(addr); } mimeMessage.addRecipients(Message.RecipientType.TO, addr); } } l = info.getCcList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.CC, addr); } } l = info.getBccList(); if (l != null) { for (int i = 0; i < l.size(); i++) { String addr = (String) l.get(i); mimeMessage.addRecipients(Message.RecipientType.BCC, addr); } } if (info.getAttachment().size() == 0) { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); mimeMessage.setText(info.getContent(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); mimeMessage.setText(info.getContent()); } mimeMessage.setContent(info.getContent(), info.getContentType()); } else { if (info.getCharSet() != null) { mimeMessage.setSubject(info.getSubject(), info.getCharSet()); } else { mimeMessage.setSubject(info.getSubject()); } Multipart mp = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); if (info.getCharSet() != null) { body.setText(info.getContent(), info.getCharSet()); body.setContent(info.getContent(), info.getContentType()); } else { body.setText(info.getContent()); body.setContent(info.getContent(), info.getContentType()); } mp.addBodyPart(body); for (int i = 0; i < info.getAttachment().size(); i++) { String filename = (String) info.getAttachment().get(i); MimeBodyPart attachment = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); attachment.setDataHandler(new DataHandler(fds)); attachment.setFileName(MimeUtility.encodeWord(fds.getName())); mp.addBodyPart(attachment); } mimeMessage.setContent(mp); } Transport.send(mimeMessage); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Error in sending email", e); } } }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java
@Override public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo()); result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationsUtil .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg);/* w w w . j a v a 2s . c o m*/ result.recordWarning(msg); return; } MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail(); String redirectToFile = mailConfigurationType.getRedirectToFile(); if (redirectToFile != null) { try { TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage)); result.recordSuccess(); } catch (IOException e) { LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile); result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e); } return; } if (mailConfigurationType.getServer().isEmpty()) { String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } long start = System.currentTimeMillis(); String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org"; for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) { OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer"); final String host = mailServerConfigurationType.getHost(); resultForServer.addContext("server", host); resultForServer.addContext("port", mailServerConfigurationType.getPort()); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (mailServerConfigurationType.getPort() != null) { properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort())); } MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType .getTransportSecurity(); boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false; switch (mailTransportSecurityType) { case STARTTLS_ENABLED: starttlsEnable = true; break; case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break; case SSL: sslEnabled = true; break; } properties.put("mail.smtp.ssl.enable", "" + sslEnabled); properties.put("mail.smtp.starttls.enable", "" + starttlsEnable); properties.put("mail.smtp.starttls.required", "" + starttlsRequired); if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) { properties.put("mail.debug", "true"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using mail properties: "); for (Object key : properties.keySet()) { if (key instanceof String && ((String) key).startsWith("mail.")) { LOGGER.debug(" - " + key + " = " + properties.get(key)); } } } task.recordState("Sending notification mail via " + host); Session session = Session.getInstance(properties); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } mimeMessage.setSubject(mailMessage.getSubject(), "utf-8"); String contentType = mailMessage.getContentType(); if (StringUtils.isEmpty(contentType)) { contentType = "text/plain; charset=UTF-8"; } mimeMessage.setContent(mailMessage.getBody(), contentType); javax.mail.Transport t = session.getTransport("smtp"); if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) { ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword(); String password = null; if (passwordProtected != null) { try { password = protector.decryptString(passwordProtected); } catch (EncryptionException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any."; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); continue; } } t.connect(mailServerConfigurationType.getUsername(), password); } else { t.connect(); } t.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + "."); resultForServer.recordSuccess(); result.recordSuccess(); long duration = System.currentTimeMillis() - start; task.recordState( "Notification mail sent successfully via " + host + ", in " + duration + " ms overall."); task.recordNotificationOperation(NAME, true, duration); return; } catch (MessagingException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any"; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); task.recordState("Error sending notification mail via " + host); } } LOGGER.warn( "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent."); result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent."); task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start); }
From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java
@Override public void notifyEmailUpdated(String oldAddress, String newAddress) { try {/*from w ww . j a v a 2 s . c om*/ //Create the message body final MimeBodyPart msg = new MimeBodyPart(); msg.setContent( "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n" + "New Email Address: " + newAddress + "\n" + "\n" + "If you have any questions, please contact your Human Resources department.", "text/plain"); final MimeMessage message = this.javaMailSender.createMimeMessage(); final Address[] recipients; if (StringUtils.isNotEmpty(oldAddress)) { recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) }; } else { recipients = new Address[] { new InternetAddress(newAddress) }; } message.setRecipients(RecipientType.TO, recipients); message.setFrom(new InternetAddress("payroll@ohr.wisc.edu")); message.setSubject("Business Email Address Change"); // sign the message body if (this.smimeSignedGenerator != null) { final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC"); message.setContent(mm, mm.getContentType()); } // no signing keystore configured, send the message unsigned else { message.setContent(msg.getContent(), msg.getContentType()); } message.saveChanges(); this.javaMailSender.send(message); this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress); } catch (Exception e) { this.logger.error( "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e); } }
From source file:fr.treeptik.cloudunit.utils.EmailUtils.java
/** * public method to send mail parameter is map with emailType, user * * @param mapConfigEmail// w w w . j a v a 2 s. c o m * @throws MessagingException */ @Async public void sendEmail(Map<String, Object> mapConfigEmail) throws MessagingException { User user = (User) mapConfigEmail.get("user"); String emailType = (String) mapConfigEmail.get("emailType"); logger.info("start email configuration for " + emailType + " to : " + user.getEmail()); logger.debug("EmailUtils : User " + user.toString()); String body = null; try { mapConfigEmail = this.initEmailConfig(mapConfigEmail); mapConfigEmail = this.defineEmailType(mapConfigEmail); body = (String) mapConfigEmail.get("body"); MimeMessage message = (MimeMessage) mapConfigEmail.get("message"); // For Spring vagrant profil, we redirect all emails // If value is not set, we use the classic configuration if (applicationContext.getEnvironment().acceptsProfiles("vagrant") && emailForceRedirect.trim().length() > 0) { message.setRecipients(Message.RecipientType.TO, emailForceRedirect); } else { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail())); } message.setContent(body, "text/html; charset=utf-8"); Transport.send(message); } catch (MessagingException e) { logger.error("Error sendEmail method - " + e); e.printStackTrace(); } logger.info("Email of " + emailType + " send to " + user.getEmail()); }
From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java
@Test public void testCurruptMessage() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SMIMEEncrypt mailet = new SMIMEEncrypt(); mailet.init(mailetConfig);//ww w . j a v a 2 s .c o m Mail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); MimeBodyPart emptyPart = new MimeBodyPart(); message.setContent(emptyPart, "text/plain"); message.saveChanges(); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("test@example.com")); mail.setRecipients(recipients); DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail); mailAttributes.setCertificates(certificates); mailet.service(mail); assertEquals(message, mail.getMessage()); try { MailUtils.validateMessage(message); fail(); } catch (IOException e) { // expected. The message should be corrupt } }
From source file:org.exoplatform.chat.server.ChatServer.java
public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject) throws Exception { String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST); String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER); String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD); String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT); Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); //props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(user, senderFullname)); // To get the array of addresses for (String to : toList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); }//from w w w. j a v a2 s. c o m message.setSubject(subject); message.setContent(htmlBody, "text/html"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } }
From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java
/** * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME * format)./*w w w. ja v a 2 s . com*/ * * @param pFrom : from field that will appear in the email header. * @param personalName : * @see {@link InternetAddress} * @param pTo : the email target destination. * @param pSubject : the subject of the email. * @param pMessage : the message or payload of the email. */ private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage, boolean htmlFormat) throws NotificationServerException { // retrieves system properties and set up Delivery Status Notification // @see RFC1891 Properties properties = System.getProperties(); properties.put("mail.smtp.host", getMailServer()); properties.put("mail.smtp.auth", String.valueOf(isAuthenticated())); javax.mail.Session session = javax.mail.Session.getInstance(properties, null); session.setDebug(isDebug()); // print on the console all SMTP messages. Transport transport = null; try { InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName); InternetAddress replyToAddress = null; InternetAddress[] toAddress = null; // parsing destination address for compliance with RFC822 try { toAddress = InternetAddress.parse(pTo, false); if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom) && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) { replyToAddress = new InternetAddress(pFrom, false); if (StringUtil.isDefined(personalName)) { replyToAddress.setPersonal(personalName, CharEncoding.UTF_8); } } } catch (AddressException e) { SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "From = " + pFrom + ", To = " + pTo); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); String subject = pSubject; if (subject == null) { subject = ""; } String content = pMessage; if (content == null) { content = ""; } email.setSubject(subject, CharEncoding.UTF_8); if (content.toLowerCase().contains("<html>") || htmlFormat) { email.setContent(content, "text/html; charset=\"UTF-8\""); } else { email.setText(content, CharEncoding.UTF_8); } email.setSentDate(new Date()); // create a Transport connection (TCP) if (isSecure()) { transport = session.getTransport(SECURE_TRANSPORT); } else { transport = session.getTransport(SIMPLE_TRANSPORT); } if (isAuthenticated()) { SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE", "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin()); transport.connect(getMailServer(), getPort(), getLogin(), getPassword()); } else { transport.connect(); } transport.sendMessage(email, toAddress); } catch (MessagingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (UnsupportedEncodingException e) { Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e); } catch (Exception e) { throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR, "smtp.EX_CANT_SEND_SMTP_MESSAGE", e); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e); } } } }
From source file:org.apache.axis.transport.mail.MailSender.java
/** * Send the soap request message to the server * * @param msgContext message context//from ww w .ja v a 2 s . c om * * @return id for the current message * @throws Exception */ private String writeUsingSMTP(MessageContext msgContext) throws Exception { String id = (new java.rmi.server.UID()).toString(); String smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST); SMTPClient client = new SMTPClient(); client.connect(smtpHost); // After connection attempt, you should check the reply code to verify // success. System.out.print(client.getReplyString()); int reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } client.login(smtpHost); System.out.print(client.getReplyString()); reply = client.getReplyCode(); if (!SMTPReply.isPositiveCompletion(reply)) { client.disconnect(); AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null); throw fault; } String fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS); String toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress)); // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) { action = ""; } Message reqMessage = msgContext.getRequestMessage(); msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action); msg.setDisposition(MimePart.INLINE); msg.setSubject(id); ByteArrayOutputStream out = new ByteArrayOutputStream(8 * 1024); reqMessage.writeTo(out); msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants())); ByteArrayOutputStream out2 = new ByteArrayOutputStream(8 * 1024); msg.writeTo(out2); client.setSender(fromAddress); System.out.print(client.getReplyString()); client.addRecipient(toAddress); System.out.print(client.getReplyString()); Writer writer = client.sendMessageData(); System.out.print(client.getReplyString()); writer.write(out2.toString()); writer.flush(); writer.close(); System.out.print(client.getReplyString()); if (!client.completePendingCommand()) { System.out.print(client.getReplyString()); AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null); throw fault; } System.out.print(client.getReplyString()); client.logout(); client.disconnect(); return id; }
From source file:com.hg.ecommerce.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type.//from w ww . j av a2s. c om * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail * @param content the body of the e-mail * @param mimeType type of message, i.e. text/plain or text/html * @throws MessagingException the exception to indicate failure */ public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { MimeMessage message = new MimeMessage(session); // n.b. any default from address is expected to be determined by caller. if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (mLogger.isDebugEnabled()) { mLogger.debug("e-mail from: " + sentFrom); } } if (to != null) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("sending e-mail to: " + to[i]); } } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("copying e-mail to: " + cc[i]); } } message.setRecipients(Message.RecipientType.CC, copyTo); } if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (mLogger.isDebugEnabled()) { mLogger.debug("blind copying e-mail to: " + bcc[i]); } } message.setRecipients(Message.RecipientType.BCC, copyTo); } message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8"); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); // Try to send while there remain some potentially good addresses do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; try { // Send to the list of remaining addresses, ignoring the addresses attached to the message Transport.send(message, remainingAddresses); } catch (SendFailedException ex) { bFailedToSome = true; sendex.setNextException(ex); // Extract the remaining potentially good addresses remainingAddresses = ex.getValidUnsentAddresses(); } } while (remainingAddresses != null && remainingAddresses.length > 0 && remainingAddresses.length != nAddresses); if (bFailedToSome) { throw sendex; } }