List of usage examples for javax.mail.internet MimeMessage addRecipients
public void addRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }//from w w w . ja v a 2 s.com if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(getPlainTextContent(), "text/plain"); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(getHtmlContent(), "text/html"); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:org.gcaldaemon.core.GmailEntry.java
public final void send(String to, String cc, String bcc, String subject, String memo, boolean html) throws Exception { MimeMessage mimeMessage = new MimeMessage(smtpSession); // Add 'to' fields StringTokenizer st = new StringTokenizer(to, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.TO, st.nextToken()); }// w w w.j av a 2 s. com // Add 'cc' fields if (cc != null && cc.length() != 0) { st = new StringTokenizer(cc, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.CC, st.nextToken()); } } // Add 'bcc' fields if (bcc != null && bcc.length() != 0) { st = new StringTokenizer(bcc, ", "); while (st.hasMoreTokens()) { mimeMessage.addRecipients(Message.RecipientType.BCC, st.nextToken()); } } // Set message if (html) { mimeMessage.setHeader("Content-Type", "text/html"); mimeMessage.setContent(memo.trim(), "text/html; charset=UTF-8"); } else { mimeMessage.setHeader("Content-Type", "text/plain"); mimeMessage.setContent(memo.trim(), "text/plain; charset=UTF-8"); } // Set 'from', 'subject' and date fields mimeMessage.setFrom(new InternetAddress(username)); mimeMessage.setSubject(subject.trim(), "UTF-8"); mimeMessage.setSentDate(new Date()); Transport.send(mimeMessage); }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * ????//from w w w . java 2 s.c o m * * @throws UnsupportedEncodingException * @throws MessagingException */ public void execute() throws UnsupportedEncodingException, MessagingException { final Session session = useDefaultSession ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator()) : Session.getInstance(properties.getProperties(), properties.getAuthenticator()); session.setDebug(isDebug); final MimeMessage message = new MimeMessage(session); message.setFrom(fromAddress.toInternetAddress(charset)); message.setReplyTo(toInternetAddresses(replyToAddressList)); message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList)); message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList)); message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList)); message.setSubject(subject, charset); setContent(message); message.setSentDate(new Date()); Transport.send(message); }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
/** * This is the actual java mail execution. * * @param notification//from w w w.j a v a2 s . c om */ private void send(EmailTemplate notification) { String from = notification.getFrom(); String to = notification.getTo(); String subject = notification.getSubject(); String style = notification.getStyle(); // body of the email is set and all substitutions of variables are made String body = notification.getBody(); // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", smtpHost); props.put("mail.smtps.port", smtpPort); props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false"); // if (smtpUseAuth) { // // props.setProperty("mail.smtp.auth", smtpUseAuth + ""); // props.setProperty("mail.username", smtpUsername); // props.setProperty("mail.password", smtpPassword); // // } // Get the default Session object. Session session = Session.getDefaultInstance(props); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); try { // Set the RFC 822 "From" header field using the // value of the InternetAddress.getLocalAddress method. message.setFrom(new InternetAddress(from)); // Add the given addresses to the specified recipient type. message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set the "Subject" header field. message.setSubject(subject); // Sets the given String as this part's content, // with a MIME type of "text/html". message.setContent(style + body, "text/html"); if (smtpUseAuth) { // Send message Transport tr = session.getTransport(smtpProtocol); tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword); message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); } else { Transport.send(message); } } catch (AddressException e) { log.error("Email Exception: Cannot connect to email host: " + smtpHost, e); } catch (MessagingException e) { log.error("Email Exception: Cannot send email message", e); } }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(/*from www .j a v a 2s .c om*/ "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:org.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }// w w w . j a v a 2 s.c om if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getBcc() != null) { message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); textBodyPart.setHeader("Content-Transfer-Encoding", "base64"); textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\""); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64"); htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\""); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!//from ww w. j a v a 2s . com * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:org.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;//from w ww. j av a 2 s . c om try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom, String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost String host = ConfigManager.getInstance().getSmtpMailhost(); String port = ConfigManager.getInstance().getSmtpMailport(); String password = ConfigManager.getInstance().getSmtpMailpassword(); String auth = ConfigManager.getInstance().getSmtpMailauth(); String sender = ConfigManager.getInstance().getSmtpMailuser(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.user", sender); properties.setProperty("mail.smtp.password", password); properties.setProperty("mail.smtp.auth", auth); properties.setProperty("mail.smtp.port", port); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. if (!StringUtils.isBlank(sender)) { try {//from w w w. ja v a2 s . c o m message.setFrom(new InternetAddress(sender)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex); } } List<Address> addresses = new ArrayList<Address>(); String receivers = emails.getReceivers(); receivers = StringUtils.trim(receivers); for (String receiver : receivers.split(";")) { if (!StringUtils.isBlank(receiver)) { try { addresses.add(new InternetAddress(receiver)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex); } } } Address[] add = new Address[addresses.size()]; addresses.toArray(add); try { message.addRecipients(Message.RecipientType.TO, add); // Set Subject: header field message.setSubject("[Pundit Contact Form]: " + subject); // Now set the actual message message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n" + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex); } // Send message try { logger.log(Level.INFO, "Trying to send message to receivers: {0}", Arrays.toString(message.getAllRecipients())); transport = session.getTransport("smtp"); transport.connect(host, sender, password); transport.sendMessage(message, message.getAllRecipients()); logger.log(Level.INFO, "Sent messages to all receivers {0}", Arrays.toString(message.getAllRecipients())); } catch (NoSuchProviderException nspe) { logger.log(Level.SEVERE, "Cannot find smtp provider", nspe); } catch (MessagingException me) { logger.log(Level.SEVERE, "Cannot set transport layer ", me); } finally { try { transport.close(); } catch (MessagingException ex) { } catch (NullPointerException ne) { } } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
@Override public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) { try {//from w w w . j a v a 2 s . co m // see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection. // following doesn't work correctly, therefore add bounce-address in message already Address convertedFrom = getRawEmailFromAddress(from); MimeMessage msg = createMessage(convertedFrom); Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"), WebappHelper.getMailConfig("mailFromName")); msg.setFrom(viewableFrom); msg.setSubject(subject, "utf-8"); // reply to can only be an address without name (at least for postfix!), see FXOLAT-312 msg.setReplyTo(new Address[] { convertedFrom }); if (tos != null && tos.length > 0) { msg.addRecipients(RecipientType.TO, tos); } if (ccs != null && ccs.length > 0) { msg.addRecipients(RecipientType.CC, ccs); } if (bccs != null && bccs.length > 0) { msg.addRecipients(RecipientType.BCC, bccs); } if (attachments != null && !attachments.isEmpty()) { // with attachment use multipart message Multipart multipart = new MimeMultipart("mixed"); // 1) add body part if (StringHelper.isHtml(body)) { Multipart alternativePart = createMultipartAlternative(body); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alternativePart); multipart.addBodyPart(wrap); } else { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); multipart.addBodyPart(messageBodyPart); } // 2) add attachments for (File attachmentFile : attachments) { // abort if attachment does not exist if (attachmentFile == null || !attachmentFile.exists()) { result.setReturnCode(MailerResult.ATTACHMENT_INVALID); logError("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null); return msg; } BodyPart filePart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFile); filePart.setDataHandler(new DataHandler(source)); filePart.setFileName(attachmentFile.getName()); multipart.addBodyPart(filePart); } // Put parts in message msg.setContent(multipart); } else { // without attachment everything is easy, just set as text if (StringHelper.isHtml(body)) { msg.setContent(createMultipartAlternative(body)); } else { msg.setText(body, "utf-8"); } } msg.setSentDate(new Date()); msg.saveChanges(); return msg; } catch (AddressException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logError("", e); return null; } catch (UnsupportedEncodingException e) { result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR); logError("", e); return null; } }