List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*from w w w . ja v a 2 s. c o m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Hospital Organization"); mimeMessage.setText(message); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (MessagingException me) { } }
From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java
/** * Send an email to the given email address with the given subject line, * using contents generated from the given template and parameters. * * @param templateName The name of the template used to generate the * contents of the email.// w w w.j a va 2 s. com * @param subject The subject for the email being sent. * @param emailAddress Sends the email to this address. * @param params The template is merged with these parameters to generate * the content of the email. * @throws EmailException Thrown if there are any errors in generating * content from the template, composing the email, or sending the email. */ private void sendMessage(final String templateName, final String subject, final String emailAddress, final Map<String, Object> params) throws EmailException { Writer stringWriter = new StringWriter(); try { Template template = this.configuration.getTemplate(templateName); template.process(params, stringWriter); } catch (TemplateException | IOException e) { throw new EmailException(e); } String content = stringWriter.toString(); MimeMessage message = new MimeMessage(this.session); try { InternetAddress fromEmailAddress = null; String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress(); if (fromEmailAddressStr != null) { fromEmailAddress = new InternetAddress(fromEmailAddressStr); } if (fromEmailAddress == null) { fromEmailAddress = InternetAddress.getLocalAddress(this.session); } if (fromEmailAddress == null) { try { fromEmailAddress = new InternetAddress( "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException ex) { fromEmailAddress = new InternetAddress("no-reply@localhost"); } } message.setFrom(fromEmailAddress); message.setSubject(subject); message.setContent(content, "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSender(fromEmailAddress); Transport.send(message); } catch (MessagingException e) { LOGGER.error("Error sending the following email message:"); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { message.writeTo(out); out.close(); } catch (IOException | MessagingException ex) { try { out.close(); } catch (IOException ignore) { } } LOGGER.error(out.toString()); throw new EmailException(e); } }
From source file:trendplot.TrendPlot.java
private void emailResults() throws IOException, WebUtilException { emailStart = System.currentTimeMillis(); ViewerConfig vc = new ViewerConfig(); if (!config.isEmpty()) { vc.setConfigFileName(config);/* w ww . j a v a 2 s .com*/ } vc.readConfig(); String host = vc.get("webserver"); if (host == null || host.isEmpty()) { host = "ldvw.ligo.caltech.edu"; } String servlet = vc.get("servlet"); if (servlet == null || servlet.isEmpty()) { servlet = "ldvw/view"; } PageItemList msg = new PageItemList(); if (!imgIds.isEmpty()) { msg.add(new PageItemHeader("The following results are available:", 3)); PageTable tbl = new PageTable(); for (int img = 0; img < imgIds.size(); img++) { PageTableRow row = new PageTableRow(); row.add(descriptions.get(img)); Integer imgId = imgIds.get(img); String url = "https://" + host + "/" + servlet + "?act=getimg&imgId=" + imgId.toString(); PageItemTextLink link = new PageItemTextLink(url, "link"); row.add(link); tbl.addRow(row); } msg.add(tbl); msg.addBlankLines(2); String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group); msg.add(new PageItemString(groupIntro, false)); String groupUrl = String.format( "https://%1$s/%2$s?act=imagehistory&group=%3$s" + "&usrSel=%4$s", host, servlet, group, user); PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page."); msg.add(groupLink); msg.addBlankLines(2); } else if (!checkOnly) { msg.add("Sorry but no images were produced."); msg.addBlankLines(2); } if (verbose || imgIds.isEmpty()) { msg.add(new PageItemString("<br>Stdout:<br><br>", false)); String outText = outStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); msg.add(new PageItemString("<br>Stderr:<br><br>", false)); outText = errStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); } msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false)); Float condor = (startTime - qtime) / 1000.f; String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor); Float overhead = (transferStart - startTime) / 1000.f; Float xfer = (plotStart - transferStart) / 1000.f; Float plot = (emailStart - plotStart) / 1000.f; String timing = String.format( "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds", condorTime, overhead, xfer, plot); outPrintWriter.println(timing); msg.addBlankLines(2); msg.add(new PageItemString(timing, false)); msg.addBlankLines(1); String msgText = msg.getHtml(); Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try { //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject("Trend plot results are available."); message.setText(msgText, "utf-8", "html"); Transport.send(message); outPrintWriter.format("Email sent to %1$s\n", email); errPrintWriter.println("Email message:"); errPrintWriter.println(msgText); } catch (MessagingException ex) { throw new WebUtilException("Cannot send email. " + ex); } }
From source file:mitm.application.djigzo.james.mailets.NotifyTest.java
@Test public void testSpecialUserPropertyRecipientUnknown() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig("test"); SendMailEventListenerImpl listener = new SendMailEventListenerImpl(); mailetConfig.getMailetContext().setSendMailEventListener(listener); String template = FileUtils.readFileToString(new File("test/resources/templates/test-user-property.ftl")); autoTransactDelegator.setProperty("test@example.com", "notifyTemplate", template); Notify mailet = new Notify(); mailetConfig.setInitParameter("template", "encryption-notification.ftl"); mailetConfig.setInitParameter("templateProperty", "notifyTemplate"); mailetConfig.setInitParameter("recipients", "${replyTo}, #{prop.recipient}"); mailet.init(mailetConfig);/* ww w. j a v a2s. c o m*/ MockMail mail = new MockMail(); MimeMessage message = MailUtils.loadMessage(new File(testBase, "mail/chinese-text.eml")); message.setFrom(new InternetAddress("test@example.com")); mail.setMessage(message); Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(new MailAddress("123@example.com")); mail.setRecipients(recipients); mail.setSender(new MailAddress("test@example.com")); mailet.service(mail); MailUtils.validateMessage(mail.getMessage()); assertEquals("[123@example.com]", MailAddressUtils.getRecipients(mail).toString()); assertTrue(TestUtils.isEqual(message, mail.getMessage())); assertEquals(1, listener.getSenders().size()); assertEquals(1, listener.getRecipients().size()); assertEquals(1, listener.getStates().size()); assertEquals(1, listener.getMessages().size()); assertEquals(1, listener.getMails().size()); assertEquals("[users@tapestry.apache.org]", listener.getRecipients().get(0).toString()); MimeMessage notification = listener.getMessages().get(0); MailUtils.validateMessage(notification); String content = (String) notification.getContent(); assertEquals("property 1 not set\nproperty 2 not set\nnon existing property not set\n", content); }
From source file:org.apache.james.James.java
/** * Generates a bounce mail that is a bounce of the original message. * * @param bounceText the text to be prepended to the message to describe the bounce condition * * @return the bounce mail/*from w w w.j a v a 2 s . c o m*/ * * @throws MessagingException if the bounce mail could not be created */ private MailImpl rawBounce(Mail mail, String bounceText) throws MessagingException { //This sends a message to the james component that is a bounce of the sent message MimeMessage original = mail.getMessage(); MimeMessage reply = (MimeMessage) original.reply(false); reply.setSubject("Re: " + original.getSubject()); reply.setSentDate(new Date()); Collection recipients = new HashSet(); recipients.add(mail.getSender()); InternetAddress addr[] = { new InternetAddress(mail.getSender().toString()) }; reply.setRecipients(Message.RecipientType.TO, addr); reply.setFrom(new InternetAddress(mail.getRecipients().iterator().next().toString())); reply.setText(bounceText); reply.setHeader(RFC2822Headers.MESSAGE_ID, "replyTo-" + mail.getName()); return new MailImpl("replyTo-" + mail.getName(), new MailAddress(mail.getRecipients().iterator().next().toString()), recipients, reply); }
From source file:org.protocoderrunner.apprunner.api.PNetwork.java
@ProtocoderScript @APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "") @APIParam(params = { "url", "function(data)" }) public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException { if (emailSettings == null) { return;//from w ww . j a va 2 s . com } // final String host = "smtp.gmail.com"; // final String address = "@gmail.com"; // final String pass = ""; Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", emailSettings.ttl); props.put("mail.smtp.host", emailSettings.host); props.put("mail.smtp.user", emailSettings.user); props.put("mail.smtp.password", emailSettings.password); props.put("mail.smtp.port", emailSettings.port); props.put("mail.smtp.auth", emailSettings.auth); Log.i("Check", "done pops"); final Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); final MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(text); Thread t = new Thread(new Runnable() { @Override public void run() { try { MLog.i("check", "transport"); Transport transport = session.getTransport("smtp"); MLog.i("check", "connecting"); transport.connect(emailSettings.host, emailSettings.user, emailSettings.password); MLog.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); MLog.i("check", "sent"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }); t.start(); }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *//*w w w .j a v a 2s.c o 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:org.opens.kbaccess.controller.utils.AMailerController.java
/** * Send a mail to the specified recipients. * //from w ww .java 2 s . c o m * @param subject The mail's subject * @param message The mail's body * @param recipients The adressee * @return true if the send succeed, * false otherwise */ public boolean sendMail(String subject, String message, String[] recipients) { Session session; MimeMessage mimeMessage; Properties properties; // sanity check if (recipients.length == 0) { return true; } // set-up session properties = new Properties(); properties.put("mail.smtp.host", mailingServiceProperties.getSmtpHost()); session = Session.getDefaultInstance(properties); //session.setDebug(true); try { Address from; Address[] to = new InternetAddress[recipients.length]; // set sender from = new InternetAddress(mailingServiceProperties.getDefaultReturnAddress()); // initialize recipients list for (int i = 0; i < to.length; ++i) { to[i] = new InternetAddress(recipients[i]); } // create message mimeMessage = new MimeMessage(session); mimeMessage.setSender(from); mimeMessage.setFrom(from); mimeMessage.setReplyTo(new Address[] { from }); mimeMessage.setRecipients(Message.RecipientType.TO, to); mimeMessage.setSubject(subject); mimeMessage.setText(message, "utf-8"); // send it Transport.send(mimeMessage); } catch (MessagingException ex) { LogFactory.getLog(GuestController.class).error("Unable to send email", ex); return false; } return true; }
From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java
@Override public void sendMailWithPreviousMailContent(final MailMetaData mailMetaData, final String text, final Message previousMailMessage) { LOGGER.debug("Sending mail with content from previous mail(MailServiceImpl)"); if (suppressMail) { return;/* w ww. ja v a 2s .com*/ } setMailProperties(); MimeMessagePreparator messagePreparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { if (null != mailMetaData.getCcAddresses() && mailMetaData.getCcAddresses().size() > 0) { setAddressToMessage(RecipientType.CC, mimeMessage, mailMetaData.getCcAddresses()); } if (null != mailMetaData.getBccAddresses() && mailMetaData.getBccAddresses().size() > 0) { setAddressToMessage(RecipientType.BCC, mimeMessage, mailMetaData.getBccAddresses()); } if (null != mailMetaData.getToAddresses() && mailMetaData.getToAddresses().size() > 0) { setAddressToMessage(RecipientType.TO, mimeMessage, mailMetaData.getToAddresses()); } if (null != mailMetaData.getFromAddress()) { mimeMessage.setFrom(new InternetAddress(new StringBuilder().append(mailMetaData.getFromName()) .append(MailConstants.LESS_SYMBOL).append(mailMetaData.getFromAddress()) .append(MailConstants.GREATER_SYMBOL).toString())); } if (null != mailMetaData.getSubject() && null != text) { mimeMessage.setSubject(mailMetaData.getSubject()); } if (null != text) { mimeMessage.setText(text); } // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(EphesoftStringUtil.concatenate(text, ORIGINAL_MAIL_MESSAGE)); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(previousMailMessage.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message mimeMessage.setContent(multipart); } }; try { mailSender.send(messagePreparator); } catch (MailException mailException) { LOGGER.error("Error while sending mail to configured mail account", mailException); throw new SendMailException( EphesoftStringUtil.concatenate("Error sending mail: ", mailMetaData.toString()), mailException); } LOGGER.info("mail sent successfully"); }
From source file:org.opencastproject.messages.MailService.java
/** Message -> MimeMessage. */ private MimeMessage toMimeMessage(Mail mail) throws Exception { final MimeMessage msg = smtpService.createMessage(); for (EmailAddress reply : mail.getReplyTo()) msg.setReplyTo(new Address[] { new InternetAddress(reply.getAddress(), reply.getName(), "UTF-8") }); // recipient/*www.j a v a 2 s . c o m*/ for (EmailAddress recipient : mail.getRecipients()) { msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient.getAddress(), recipient.getName(), "UTF-8")); } // subject msg.setSubject(mail.getSubject()); EmailAddress from = mail.getSender(); msg.setFrom(new InternetAddress(from.getAddress(), from.getName(), "UTF-8")); // body msg.setText(mail.getBody(), "UTF-8"); return msg; }