List of usage examples for javax.mail.internet InternetAddress parse
public static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException
From source file:EmailJndiServlet.java
private void sendMessage(String to, String from, String subject, String bodyContent) throws Exception { Message mailMsg = null;/*w w w . j av a2 s .c om*/ synchronized (mailSession) { mailMsg = new MimeMessage(mailSession);//a new email message } InternetAddress[] addresses = null; try { if (to != null) { //throws 'AddressException' if the 'to' email address //violates RFC822 syntax addresses = InternetAddress.parse(to, false); mailMsg.setRecipients(Message.RecipientType.TO, addresses); } else { throw new MessagingException("The mail message requires a 'To' address."); } if (from != null) mailMsg.setFrom(new InternetAddress(from)); if (subject != null) mailMsg.setSubject(subject); if (bodyContent != null) mailMsg.setText(bodyContent); //Finally, send the mail message; throws a 'SendFailedException' //if any of the message's recipients have an invalid adress Transport.send(mailMsg); } catch (Exception exc) { throw exc; } }
From source file:de.fzi.ALERT.actor.ActionActuator.MailService.java
public void sendEmail(Authenticator auth, String address, String subject, String content) { try {//from www . j a va 2s.c om Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", true); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props, auth); // -- Create a new message -- Message msg = new MimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress(username)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false)); // -- Set the subject and body text -- msg.setSubject(subject); msg.setText(content); // -- Set some other header information -- msg.setHeader("X-Mailer", "LOTONtechEmail"); msg.setSentDate(new Date()); // -- Send the message -- Transport.send(msg); System.out.println("An announce Mail has been send to " + address); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:common.email.MailServiceImpl.java
/** * this method sends email using a given template * @param subject subject of a mail//from w w w. j a va2s. c om * @param recipientEmail email receiver adress * @param mail mail text to send * @param from will be set * @return true if send succeed * @throws java.io.FileNotFoundException * @throws java.io.IOException */ protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException { try { Properties props = new Properties(); //props.put("mailHost", mailHost); Session session = Session.getInstance(props); // construct the message javax.mail.Message msg = new javax.mail.internet.MimeMessage(session); if (from == null) { msg.setFrom(); } else { try { msg.setFrom(new InternetAddress(from)); } catch (MessagingException ex) { logger.error(ex); } } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); msg.setSubject(subject); msg.setSentDate(new Date()); //msg.setHeader("", user) msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8"))); SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); t.connect(mailHost, user, password); Address[] a = msg.getAllRecipients(); t.sendMessage(msg, a); t.close(); return true; } catch (MessagingException ex) { logger.error(ex); ex.printStackTrace(); return false; } }
From source file:org.echocat.jomon.net.mail.Mail.java
@Nonnull public Mail withRecipients(@Nonnull RecipientType type, @Nullable String... recipients) { if (!isEmpty(recipients)) { final List<InternetAddress> recipientsAsAddress = new ArrayList<>(recipients.length); for (int i = 0; i < recipients.length; i++) { try { addAll(recipientsAsAddress, InternetAddress.parse(recipients[i], true)); } catch (final AddressException e) { throw new IllegalArgumentException("Illegal recipient: " + recipients[i], e); }/* w w w .j av a 2s. co m*/ } withRecipients(type, recipientsAsAddress.toArray(new InternetAddress[recipientsAsAddress.size()])); } return thisInstance(); }
From source file:org.intermine.util.MailUtils.java
/** * Send an email to an address, supplying the recipient, subject and body. * * @param to the address to send to/* w w w . j a va 2 s .c om*/ * @param subject The Subject of the email * @param body The content of the email * @param from the address to send from * @param webProperties Common properties for all emails (such as from, authentication) * @throws MessagingException if there is a problem creating the email */ public static void email(String to, String subject, String body, String from, final Properties webProperties) throws MessagingException { final String user = webProperties.getProperty("mail.smtp.user"); String smtpPort = webProperties.getProperty("mail.smtp.port"); String authFlag = webProperties.getProperty("mail.smtp.auth"); String starttlsFlag = webProperties.getProperty("mail.smtp.starttls.enable"); Properties properties = System.getProperties(); properties.put("mail.smtp.host", webProperties.get("mail.host")); properties.put("mail.smtp.user", user); // Fix to "javax.mail.MessagingException: 501 Syntactically // invalid HELO argument(s)" problem // See http://forum.java.sun.com/thread.jspa?threadID=487000&messageID=2280968 properties.put("mail.smtp.localhost", "localhost"); if (smtpPort != null) { properties.put("mail.smtp.port", smtpPort); } if (starttlsFlag != null) { properties.put("mail.smtp.starttls.enable", starttlsFlag); } if (authFlag != null) { properties.put("mail.smtp.auth", authFlag); } Session session; if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) { Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String password = (String) webProperties.get("mail.server.password"); return new PasswordAuthentication(user, password); } }; session = Session.getInstance(properties, authenticator); } else { session = Session.getInstance(properties); } MimeMessage message = new MimeMessage(session); if (StringUtils.isEmpty(user)) { message.setFrom(new InternetAddress(from)); } else { message.setReplyTo(InternetAddress.parse(from, true)); message.setFrom(new InternetAddress(user)); } message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]); message.setSubject(subject); message.setContent(body, "text/plain"); Transport.send(message); }
From source file:org.cgiar.ccafs.marlo.action.TestSMTPAction.java
@Override public String execute() throws Exception { Properties properties = System.getProperties(); properties.put("mail.smtp.host", config.getEmailHost()); properties.put("mail.smtp.port", config.getEmailPort()); Session session = Session.getInstance(properties, new Authenticator() { @Override/*from ww w . j a v a2s . c om*/ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getEmailUsername(), config.getEmailPassword()); } }); // Create a new message MimeMessage msg = new MimeMessage(session) { @Override protected void updateMessageID() throws MessagingException { if (this.getHeader("Message-ID") == null) { super.updateMessageID(); } } }; msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("h.jimenez@cgiar.org", false)); msg.setSubject("Test email"); msg.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("If you receive this email, it means that the server is working correctly.", "text; charset=utf-8"); Thread thread = new Thread() { @Override public void run() { sent = false; int i = 0; while (!sent) { try { Transport.send(sendMail); LOG.info("Message sent TRIED#: " + i + " \n" + "Test email"); sent = true; } catch (MessagingException e) { LOG.info("Message DON'T sent: \n" + "Test email"); i++; if (i == 10) { break; } try { Thread.sleep(1 * // minutes to sleep 60 * // seconds to a minute 1000); } catch (InterruptedException e1) { e1.printStackTrace(); } e.printStackTrace(); } } }; }; thread.run(); if (sent) { return SUCCESS; } else { return INPUT; } }
From source file:org.openmrs.notification.mail.MailMessageSender.java
/** * Converts the message object to a mime message in order to prepare it to be sent. * * @param message//from ww w . j a v a 2s . c o m * @return MimeMessage */ public MimeMessage createMimeMessage(Message message) throws Exception { if (message.getRecipients() == null) { throw new MessageException("Message must contain at least one recipient"); } // set the content-type to the default if it isn't defined in Message if (!StringUtils.hasText(message.getContentType())) { String contentType = Context.getAdministrationService().getGlobalProperty("mail.default_content_type"); message.setContentType(StringUtils.hasText(contentType) ? contentType : "text/plain"); } MimeMessage mimeMessage = new MimeMessage(session); // TODO Need to test the null case. // Transport should use default mail.from value defined in properties. if (message.getSender() != null) { mimeMessage.setSender(new InternetAddress(message.getSender())); } mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(message.getRecipients(), false)); mimeMessage.setSubject(message.getSubject()); if (!message.hasAttachment()) { mimeMessage.setContent(message.getContent(), message.getContentType()); } else { mimeMessage.setContent(createMultipart(message)); } return mimeMessage; }
From source file:org.xwiki.contrib.mailarchive.utils.internal.MailUtils.java
@Override public IMAUser parseUser(final String user, final boolean isMatchLdap) { logger.debug("parseUser {}, {}", user, isMatchLdap); MAUser maUser = new MAUser(); maUser.setOriginalAddress(user);/* w ww . jav a2 s .c o m*/ if (StringUtils.isBlank(user)) { return maUser; } String address = null; String personal = null; // Do our best to extract an address and a personal try { InternetAddress ia = null; InternetAddress[] result = InternetAddress.parse(user, true); if (result != null && result.length > 0) { ia = result[0]; if (!StringUtils.isBlank(ia.getAddress())) { address = ia.getAddress(); } if (!StringUtils.isBlank(ia.getPersonal())) { personal = ia.getPersonal(); } } } catch (AddressException e) { logger.info("Email Address does not follow standards : " + user); } if (StringUtils.isBlank(address)) { String[] substrs = StringUtils.substringsBetween(user, "<", ">"); if (substrs != null && substrs.length > 0) { address = substrs[0]; } else { // nothing matches, we suppose recipient only contains email address address = user; } } if (StringUtils.isBlank(personal)) { if (user.contains("<")) { personal = StringUtils.substringBeforeLast(user, "<"); if (StringUtils.isBlank(personal)) { personal = StringUtils.substringBefore(address, "@"); } } } maUser.setAddress(address); maUser.setDisplayName(personal); // Now to match a wiki profile logger.debug("parseUser extracted email {}", address); String parsedUser = null; if (!StringUtils.isBlank(address)) { // to match "-external" emails and old mails with '@gemplus.com'... String pattern = address.toLowerCase(); pattern = pattern.replace("-external", "").replaceAll("^(.*)@.*[.]com$", "$1%@%.com"); logger.debug("parseUser pattern applied {}", pattern); // Try to find a wiki profile with this email as parameter. // TBD : do this in the loading phase, and only try to search db if it was not found ? String xwql = "select doc.fullName from Document doc, doc.object(XWiki.XWikiUsers) as user where LOWER(user.email) like :pattern"; List<String> profiles = null; try { profiles = queryManager.createQuery(xwql, Query.XWQL).bindValue("pattern", pattern).execute(); } catch (QueryException e) { logger.warn("parseUser Query threw exception", e); profiles = null; } if (profiles == null || profiles.size() == 0) { logger.debug("parseUser found no wiki profile from db"); return maUser; } else { if (isMatchLdap) { logger.debug("parseUser Checking for LDAP authenticated profile(s) ..."); // If there exists one, we prefer the user that's been authenticated through LDAP for (String usr : profiles) { if (bridge.exists(usr, "XWiki.LDAPProfileClass")) { parsedUser = usr; logger.debug("parseUser Found LDAP authenticated profile {}", parsedUser); } } if (parsedUser != null) { maUser.setWikiProfile(parsedUser); logger.debug("parseUser return {}", maUser); return maUser; } } } // If none has authenticated from LDAP, we return the first user found maUser.setWikiProfile(profiles.get(0)); logger.debug("parseUser return {}", maUser); return maUser; } else { logger.debug("parseUser No email found to match"); return maUser; } }
From source file:org.kuali.rice.kcb.service.impl.EmailServiceImpl.java
/** * First constructs the appropriately formatted mail message then sends it off. * @see org.kuali.rice.kcb.service.EmailService#sendNotificationEmail(org.kuali.rice.kcb.bo.MessageDelivery, java.lang.String, java.lang.String) *//*from w w w . j a va 2s. c o m*/ public Long sendEmail(MessageDelivery messageDelivery, String recipientEmailAddress, String emailFormat) throws Exception { // reconcile the need for custom rendering depending on message producer // or can we just have a single URL that redirects to original dochandler? Message message = messageDelivery.getMessage(); String channelName = message.getChannel(); String producer = message.getProducer(); String sender = defaultSender; if (producer != null) { try { InternetAddress[] addresses = InternetAddress.parse(producer, false); if (addresses.length > 0) { sender = addresses[0].toString(); } } catch (AddressException ae) { // not a valid email address } } String title = messageDelivery.getMessage().getTitle(); String subject = (channelName == null ? "" : channelName + " ") + (!StringUtils.isBlank(title) ? " - " + title : ""); String format = FORMAT_TEXT_PLAIN; String linebreak = "\n\n"; // NOTE: we don't set the docId parameter in the link // This forces the detail view to not render an acknowledge // button String link = weburl + "/" + DETAILACTION + "?" + NotificationConstants.NOTIFICATION_CONTROLLER_CONSTANTS.MSG_DELIVERY_ID + "=" + messageDelivery.getId(); if (emailFormat == null || emailFormat.equals("text")) { // defaults values are good for text } else { // html format format = FORMAT_TEXT_HTML; link = "<a href='" + link + "'>Notification Detail</a>"; linebreak = "<br /><br />"; } LOG.debug("link: " + link); // construct the message StringBuffer sb = new StringBuffer(); sb.append("You have a new notification. Click the link below to review its details."); sb.append(linebreak); sb.append(linebreak); sb.append(link); String content = sb.toString(); LOG.debug("subject: " + subject); LOG.debug("sender: " + sender); LOG.debug("recipient: " + recipientEmailAddress); LOG.debug("content: " + content); // actually do the send mailer.sendEmail(new EmailFrom(sender), new EmailTo(recipientEmailAddress), new EmailSubject(subject), new EmailBody(content), !FORMAT_TEXT_PLAIN.equals(format)); return null; }
From source file:com.mnt.base.mail.MailHelper.java
public static void sendMail(String mailType, String mailTos, Map<String, Object> infoMap) { String[] mailtemplate = loadMailTemplate(mailType); if (mailtemplate != null && mailtemplate.length == 2) { String from = BaseConfiguration.getProperty("mail_server_email"); String subject = buildMailContent(mailtemplate[0], infoMap, false); String mailContent = buildMailContent(mailtemplate[1], infoMap, true); Message msg = new MimeMessage(smtpSession); try {//w w w.ja va2s. c o m msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTos, false)); msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B")); msg.setContent(mailContent, "text/html;charset=UTF-8"); msg.setSentDate(new Date()); Transport.send(msg); } catch (Exception e) { log.error("fail to send the mail: " + msg, e); } } }