List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.mobicents.servlet.restcomm.email.EmailService.java
EmailResponse send(final Mail mail) { try {/* w w w .jav a 2s . com*/ InternetAddress from; if (mail.from() != null || !mail.from().equalsIgnoreCase("")) { from = new InternetAddress(mail.from()); } else { from = new InternetAddress(user); } final InternetAddress to = new InternetAddress(mail.to()); final MimeMessage email = new MimeMessage(session); email.setFrom(from); email.addRecipient(Message.RecipientType.TO, to); email.setSubject(mail.subject()); email.setText(mail.body()); email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false)); email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false)); Transport.send(email); return new EmailResponse(mail); } catch (final MessagingException exception) { logger.error(exception.getMessage(), exception); return new EmailResponse(exception, exception.getMessage()); } }
From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java
/** * Performs some action on the given report * @param report the Report to process/*from w w w . j a v a2 s. com*/ */ public void process(Report report, Properties configuration) { try { Message m = new MimeMessage(getSession()); m.setFrom(new InternetAddress(configuration.getProperty("from"))); for (String recipient : configuration.getProperty("to", "").split("\\,")) { m.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } // TODO: Make these such that they can contain report information m.setSubject(configuration.getProperty("subject")); Multipart multipart = new MimeMultipart(); MimeBodyPart contentBodyPart = new MimeBodyPart(); String content = configuration.getProperty("content", ""); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) { content += new String(report.getRenderedOutput()); } contentBodyPart.setContent(content, "text/html"); multipart.addBodyPart(contentBodyPart); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) { MimeBodyPart attachment = new MimeBodyPart(); Object output = report.getRenderedOutput(); if (report.getOutputContentType().contains("text")) { output = new String(report.getRenderedOutput(), "UTF-8"); } attachment.setDataHandler(new DataHandler(output, report.getOutputContentType())); attachment.setFileName(configuration.getProperty("attachmentName")); multipart.addBodyPart(attachment); } m.setContent(multipart); Transport.send(m); } catch (Exception e) { throw new RuntimeException("Error occurred while sending report over email", e); } }
From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;/* www . j a va 2 s . c o m*/ } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();/*from w w w. j a va2s . c o m*/ MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
From source file:org.b3log.solo.mail.local.MailSender.java
/** * Sends email.//from ww w. jav a2s . c o m * * @param message the specified message * @throws Exception message exception */ void sendMail(final Message message) throws Exception { final javax.mail.Message msg = convert2JavaMailMsg(message); Transport.send(msg); }
From source file:org.openmrs.module.sync.SyncMailUtil.java
/** * Sends a message using the current mail session *///from w ww . j av a 2 s . c o m public static void sendMessage(String recipients, String subject, String body) throws MessageException { try { Message message = new MimeMessage(getMailSession()); message.setSentDate(new Date()); if (StringUtils.isNotBlank(subject)) { message.setSubject(subject); } if (StringUtils.isNotBlank(recipients)) { for (String recipient : recipients.split("\\,")) { message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipient)); } } if (StringUtils.isNotBlank(body)) { Multipart multipart = new MimeMultipart(); MimeBodyPart contentBodyPart = new MimeBodyPart(); contentBodyPart.setContent(body, "text/html"); multipart.addBodyPart(contentBodyPart); message.setContent(multipart); } log.info("Sending email with subject <" + subject + "> to <" + recipients + ">"); log.debug("Mail has contents: \n" + body); Transport.send(message); log.debug("Message sent without errors"); } catch (Exception e) { log.error("Message could not be sent due to " + e.getMessage(), e); throw new MessageException(e); } }
From source file:com.app.mail.DefaultMailSender.java
@Override public void sendSearchResultsToRecipient(int userId, Map<SearchQuery, List<SearchResult>> searchQueryResultMap) throws DatabaseConnectionException, SQLException { User user = UserUtil.getUserByUserId(userId); if (!user.isEmailNotification()) { return;// ww w . j av a 2s . c o m } int emailsSent = user.getEmailsSent(); if (emailsSent >= PropertiesValues.NUMBER_OF_EMAILS_PER_DAY) { _log.info("User ID: {} has reached their email limit for the day", user.getUserId()); return; } _log.debug("Sending search results for {} queries for userId: {}", searchQueryResultMap.size(), userId); Session session = _authenticateOutboundEmailAddress(); try { Message emailMessage = _populateEmailMessage(searchQueryResultMap, user.getEmailAddress(), user.getUnsubscribeToken(), session); Transport.send(emailMessage); emailsSent++; } catch (Exception e) { _log.error("Unable to send search results to userId: " + userId, e); } UserUtil.updateEmailsSent(user.getUserId(), emailsSent); }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }/*from ww w. j a va 2 s . c o m*/ String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:at.molindo.notify.channel.mail.AbstractMailClient.java
/** * override for testing */ protected void send(MimeMessage mm) throws MessagingException { Transport.send(mm); }
From source file:dk.netarkivet.common.utils.EMailUtils.java
/** * Send an email, possibly forgiving errors. * * @param to The recipient of the email. Separate multiple recipients with * commas. Supports only adresses of the type 'john@doe.dk', not * 'John Doe <john@doe.dk>' * @param from The sender of the email.//from w w w . j a va 2 s . co m * @param subject The subject of the email. * @param body The body of the email. * @param forgive On true, will send the email even on invalid email * addresses, if at least one recipient can be set, on false, will * throw exceptions on any invalid email address. * * * @throws ArgumentNotValid If either parameter is null, if to, from or * subject is the empty string, or no recipient * can be set. If "forgive" is false, also on * any invalid to or from address. * @throws IOFailure If the message cannot be sent for some reason. */ public static void sendEmail(String to, String from, String subject, String body, boolean forgive) { ArgumentNotValid.checkNotNullOrEmpty(to, "String to"); ArgumentNotValid.checkNotNullOrEmpty(from, "String from"); ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject"); ArgumentNotValid.checkNotNull(body, "String body"); Properties props = new Properties(); props.put(MAIL_FROM_PROPERTY_KEY, from); props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER)); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); // to might contain more than one e-mail address for (String toAddressS : to.split(",")) { try { InternetAddress toAddress = new InternetAddress(toAddressS.trim()); msg.addRecipient(Message.RecipientType.TO, toAddress); } catch (AddressException e) { if (forgive) { log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address", e); } } catch (MessagingException e) { if (forgive) { log.warn("To address '" + toAddressS + "' could not be set in email", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e); } } } try { if (msg.getAllRecipients().length == 0) { throw new ArgumentNotValid("No valid recipients in '" + to + "'"); } } catch (MessagingException e) { throw new ArgumentNotValid("Message invalid after setting" + " recipients", e); } try { InternetAddress fromAddress = null; fromAddress = new InternetAddress(from); msg.setFrom(fromAddress); } catch (AddressException e) { throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e); } catch (MessagingException e) { if (forgive) { log.warn("From address '" + from + "' could not be set in email", e); } else { throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e); } } try { msg.setSubject(subject); msg.setContent(body, MIMETYPE); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to + "'. Body:\n" + body, e); } }