List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:org.cern.flume.sink.mail.MailSink.java
@Override public Status process() throws EventDeliveryException { Status status = null;//from w ww . ja v a2 s .com // Start transaction Channel ch = getChannel(); Transaction txn = ch.getTransaction(); txn.begin(); try { Event event = ch.take(); if (event != null) { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From: header field of the header. mimeMessage.setFrom(new InternetAddress(sender)); // Set To: header field of the header. for (String recipient : recipients) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } // Now set the subject and actual message Map<String, String> headers = event.getHeaders(); String value; String mailSubject = subject; for (String field : subjectFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailSubject = mailSubject.replace("%{" + field + "}", value); } String mailMessage = message; for (String field : messageFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailMessage = mailMessage.replace("%{" + field + "}", value); } mimeMessage.setSubject(mailSubject); mimeMessage.setText(mailMessage); // Send message Transport.send(mimeMessage); } txn.commit(); status = Status.READY; } catch (Throwable t) { txn.rollback(); logger.error("Unable to send e-mail.", t); status = Status.BACKOFF; if (t instanceof Error) { throw (Error) t; } } finally { txn.close(); } return status; }
From source file:org.eclipse.ecr.automation.core.mail.Mailer.java
/** * Send a single email.//from w ww.j a v a2s. c o m */ public void sendEmail(String from, String to, String subject, String body) throws MessagingException { // Here, no Authenticator argument is used (it is null). // Authenticators are used to prompt the user for user // name and password. MimeMessage message = new MimeMessage(getSession()); // 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(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(body); Transport.send(message); }
From source file:com.threewks.thundr.gmail.GmailMailer.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email. * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException/* w w w . j ava 2 s . c o m*/ */ protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from, Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject, String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); try { email.setFrom(from); if (to != null) { email.addRecipients(javax.mail.Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()])); } if (cc != null) { email.addRecipients(javax.mail.Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()])); } if (bcc != null) { email.addRecipients(javax.mail.Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); } if (replyTo != null) { email.setReplyTo(new Address[] { replyTo }); } email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); if (attachments != null) { for (com.threewks.thundr.mail.Attachment attachment : attachments) { mimeBodyPart = new MimeBodyPart(); BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry); renderer.render(attachment.view()); byte[] data = renderer.getOutputAsBytes(); String attachmentContentType = renderer.getContentType(); String attachmentCharacterEncoding = renderer.getCharacterEncoding(); populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType, attachmentCharacterEncoding); multipart.addBodyPart(mimeBodyPart); } } email.setContent(multipart); } catch (MessagingException e) { Logger.error(e.getMessage()); Logger.error( "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d", from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to), Transformers.InternetAddressesToString.from(cc), Transformers.InternetAddressesToString.from(bcc), replyTo == null ? "null" : replyTo.getAddress(), replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText, attachments == null ? 0 : attachments.size()); throw new GmailException(e); } return email; }
From source file:de.helmholtz_muenchen.ibis.utils.abstractNodes.HTExecutorNode.HTExecutorNodeModel.java
private void sendMail(String content) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", emailhost); Session session = Session.getDefaultInstance(properties); try {//from w w w . j a v a 2 s .co m MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailsender)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject(HEADER); message.setText(content); Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:cz.filmtit.userspace.Emailer.java
/** * Sends an email with parameters that has been collected before in the fields of the class. * @return Sign if the email has been successfully sent */// ww w . j a v a 2s .c o m public boolean send() { if (hasCollectedData()) { // send mail; javax.mail.Session session; logger.info("Emailer", "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address") + " password" + (String) configuration.getProperty("mail.filmtit.password")); session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); } }); session.setDebug(true); javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); try { message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email)); message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address"))); message.setSubject(this.subject); message.setText(this.message); Transport transportSSL = session.getTransport(); transportSSL.connect((String) configuration.getProperty("mail.smtps.host"), Integer.parseInt(configuration.getProperty("mail.smtps.port")), (String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); // account used transportSSL.sendMessage(message, message.getAllRecipients()); transportSSL.close(); } catch (MessagingException ex) { logger.error("Emailer", "An error while sending an email. " + ex); } return true; } logger.warning("Emailer", "Emailer has not collected all data to be able to send an email."); return false; }
From source file:pt.webdetails.cdv.notifications.EmailOutlet.java
private void applyMessageHeaders(final MimeMessage msg, Alert alert) throws MessagingException { String from = getSetting("from"), to = getSetting("to"), cc = getSetting("cc"), bcc = getSetting("bcc"), subject = getSubject(alert); msg.setFrom(new InternetAddress(from)); 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)); }/*from w w w.j av a 2 s.c o m*/ if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, CharsetHelper.getEncoding()); } }
From source file:rescustomerservices.GmailQuickstart.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.//from ww w . ja v a2 s . c o m * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:ro.agrade.jira.qanda.listeners.DirectEmailMessageHandler.java
@Override protected void sendMail(String[] recipients, String subject, String message, String from) throws MessagingException { SMTPMailServer server = mailServerManager.getDefaultSMTPMailServer(); if (server == null) { LOG.debug("Email server is not configured. QandA is unable to send mails ..."); return;/*from ww w.jav a2 s. c om*/ } LOG.debug("Email message: initializing."); //Set the host smtp address Properties props = new Properties(); String proto = server.getMailProtocol().getProtocol(); props.put("mail.transport.protocol", proto); props.put("mail." + proto + ".host", server.getHostname()); props.put("mail." + proto + ".port", server.getPort()); String username = server.getUsername(); String password = server.getPassword(); Authenticator auth = null; if (username != null && password != null) { auth = new SMTPAuthenticator(username, password); props.put("mail." + proto + ".auth", "true"); } Session session; try { session = auth != null ? Session.getDefaultInstance(props, auth) : Session.getDefaultInstance(props); } catch (SecurityException ex) { LOG.warn("Could not get default session. Attempting to create a new one."); session = auth != null ? Session.getInstance(props, auth) : Session.getInstance(props); } // create a message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from == null) { from = server.getDefaultFrom(); } // set the from address if (from != null) { InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); } if (recipients != null && recipients.length > 0) { // set TO address(es) InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); } // Setting the Subject msg.setSubject(subject); // Setting text content MimeBodyPart contentPart = new MimeBodyPart(); contentPart.setContent(message, "text/html; charset=utf-8"); multipart.addBodyPart(contentPart); msg.setContent(multipart); Transport.send(msg); LOG.debug("Email message sent successfully."); }
From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java
/** * @param runner/* w w w . j a v a2 s .co m*/ * @param resultDir * @throws MessagingException * @throws IOException */ public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setHeader("Content-Transfer-Encoding", "7bit"); // To mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo())); // From mimeMessage.setFrom(new InternetAddress(config.getFrom())); HashMap<String, Object> context = new HashMap<String, Object>(); context.put("result", runner.getResult() ? "passed" : "failed"); context.put("passedCount", new Integer(runner.getPassedCount())); context.put("failedCount", new Integer(runner.getFailedCount())); context.put("totalCount", new Integer(runner.getHtmlSuiteList().size())); context.put("startTime", new Date(runner.getStartTime())); context.put("endTime", new Date(runner.getEndTime())); context.put("htmlSuites", runner.getHtmlSuiteList()); // subject mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset()); // multipart message MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset()); content.addBodyPart(body); File resultArchive = createResultArchive(resultDir); MimeBodyPart attachmentFile = new MimeBodyPart(); attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive))); attachmentFile.setFileName(RESULT_ARCHIVE_FILE); content.addBodyPart(attachmentFile); mimeMessage.setContent(content); // send mail _send(mimeMessage); }
From source file:org.cloudcoder.healthmonitor.HealthMonitor.java
private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews, boolean badNews, String reportEmailAddress) throws MessagingException, AddressException { Session session = createMailSession(config); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(reportEmailAddress)); message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress)); message.setSubject("CloudCoder health monitor report"); StringBuilder body = new StringBuilder(); body.append("<h1>CloudCoder health monitor report</h1>\n"); if (badNews) { body.append("<h2>Unhealthy instances</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.badNews()) { appendReportItem(body, item, infoMap); }/*from w ww . ja v a 2s . co m*/ } body.append("</ul>\n"); } if (goodNews) { body.append("<h2>Healthy instances (back on line)</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.goodNews()) { appendReportItem(body, item, infoMap); } } body.append("</ul>\n"); } message.setContent(body.toString(), "text/html"); Transport.send(message); }