List of usage examples for javax.mail.internet MimeMessage setRecipients
public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:org.bibsonomy.util.MailUtils.java
/** * Sends a mail to the given recipients//from www .ja v a 2s. c o m * * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendMail(final String[] recipients, final String subject, final String message, final String from) throws MessagingException { boolean debug = false; // create some properties and get the default Session final Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message final MimeMessage msg = new MimeMessage(session); // set the from and to address final InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); final 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); // Optional : You can also set your custom headers in the Email if you Want //msg.addHeader("X-Sent-By", "Bibsonomy-Bot"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message, "UTF-8"); Transport.send(msg); }
From source file:fr.treeptik.cloudunit.utils.EmailUtils.java
/** * public method to send mail parameter is map with emailType, user * * @param mapConfigEmail/*from w w w . ja va 2 s .co 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:org.pentaho.platform.scheduler2.email.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {//from w w w. j a v a 2s . c o m // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { 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)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:org.fireflow.service.email.send.MailSenderImpl.java
/** * TODO ?//www.j a v a 2s . com * @param mailSession * @param mailMessage * @return * @throws MessagingException * @throws AddressException * @throws ServiceInvocationException */ private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage) throws AddressException, MessagingException { MimeMessage mimeMsg = new MimeMessage(mailSession); //1?set from //Assert.notNull(mailMessage.getFrom(),"From address must not be null"); mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom())); //2?set mailto List<String> mailToList = mailMessage.getMailToList(); InternetAddress[] addressList = new InternetAddress[mailToList.size()]; for (int i = 0; i < mailToList.size(); i++) { String mailTo = mailToList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.TO, addressList); //3?set cc List<String> ccList = mailMessage.getCarbonCopyList(); if (ccList != null && ccList.size() > 0) { addressList = new InternetAddress[ccList.size()]; for (int i = 0; i < ccList.size(); i++) { String mailTo = ccList.get(i); addressList[i] = new InternetAddress(mailTo); } mimeMsg.setRecipients(Message.RecipientType.CC, addressList); } //4?set subject mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset()); //5?set sentDate if (this.sentDate != null) { mimeMsg.setSentDate(sentDate); } //6?set email body Multipart multiPart = new MimeMultipart(); MimeBodyPart bp = new MimeBodyPart(); if (mailMessage.getBodyIsHtml()) bp.setContent(mailMessage.getBody(), CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset()); else bp.setText(mailMessage.getBody(), mailServiceDef.getCharset()); multiPart.addBodyPart(bp); mimeMsg.setContent(multiPart); //7?set attachment //TODO ? return mimeMsg; }
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 w w w . j av a 2 s . co m } 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:org.apache.james.mailetcontainer.impl.JamesMailetContext.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/*from w w w.j a va 2s . c o m*/ * @return the bounce mail * @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<MailAddress> recipients = new HashSet<MailAddress>(); 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.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java
@Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws IOException, InterruptedException { final EnvVars env = build.getEnvironment(listener); final String charset = Mailer.descriptor().getCharset(); final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession()); try {/*from w ww.j a va 2 s . c o m*/ msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset)); msg.setContent("", "text/plain"); msg.setSentDate(new Date()); String actualReplyTo = env.expand(replyTo); if (StringUtils.isBlank(actualReplyTo)) { actualReplyTo = Mailer.descriptor().getReplyToAddress(); } if (StringUtils.isNotBlank(actualReplyTo)) { msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) }); } msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset)); msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset)); msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset)); msg.setSubject(env.expand(subject), charset); msg.setText(env.expand(text), charset); Transport.send(msg); } catch (final MessagingException e) { listener.getLogger().println(Messages.SendMail_FailedToSend()); e.printStackTrace(listener.error(e.getMessage())); return false; } listener.getLogger().println(Messages.SendMail_SentSuccessfully()); return true; }
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined/*from w ww . jav a2 s .c om*/ * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale); final String html = composeDeclineMailMessage(team, locale, "html"); final String plainText = composeDeclineMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined/*w w w . ja v a 2s . co m*/ * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale); final String html = composeAcceptMailMessage(team, locale, "html"); final String plainText = composeAcceptMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int send(Mail mail) { Session session = null;// ww w .j a v a 2s. c om Transport transport = null; if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo())) && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc())) && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) { logger.error("This mail has no recipient"); return 0; } if (mail.getContents().size() == 0) { logger.error("This mail is empty. You should add a content"); return 0; } try { if ((transport == null) || (session == null)) { logger.info("Sending mail : Initializing properties"); Properties props = initProperties(); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (session.getProperty("mail.smtp.auth") == "true") transport.connect(session.getProperty("mail.smtp.server.username"), session.getProperty("mail.smtp.server.password")); else transport.connect(); try { Multipart wrapper = generateMimeMultipart(mail); InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo()); MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setSubject(mail.getSubject()); message.setFrom(new InternetAddress(mail.getFrom())); message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo); if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) { logger.info("Adding ReplyTo field"); InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo()); if (adressesReplyTo.length != 0) message.setReplyTo(adressesReplyTo); } if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) { logger.info("Adding Cc recipients"); InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc()); if (adressesCc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc); } if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) { InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc()); if (adressesBcc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc); } message.setContent(wrapper); message.setSentDate(new Date()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (SendFailedException sfex) { logger.error("Error encountered while trying to send the mail"); logger.error("SendFailedException has occured.", sfex); try { transport.close(); } catch (MessagingException Mex) { logger.error("MessagingException has occured.", Mex); } return 0; } catch (MessagingException mex) { logger.error("Error encountered while trying to send the mail"); logger.error("MessagingException has occured.", mex); try { transport.close(); } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } } } catch (Exception e) { System.out.println(e.toString()); logger.error("Error encountered while trying to setup mail properties"); try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } return 1; }