List of usage examples for javax.mail.internet AddressException toString
@Override
public String toString()
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc/*w ww.j a va 2s .co m*/ */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message's content simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.redhat.rhn.manager.user.UpdateUserCommand.java
/** * Private helper method to validate the user's email address. Puts errors into the * errors list.// w w w . j a va2 s . c o m */ private void validateEmail() { if (!emailChanged) { return; // nothing to verify } // Make sure user and email are not null if (email == null) { throw new IllegalArgumentException("Email address is null"); } // Make email is not over the max length if (user.getEmail().length() > UserDefaults.get().getMaxEmailLength()) { throw new IllegalArgumentException( String.format("Email address specified [%s] is too long", user.getEmail())); } // Make sure set email is valid try { new InternetAddress(email).validate(); } catch (AddressException e) { throw new IllegalArgumentException("Email address invalid. Cause: " + e.toString()); } }
From source file:com.redhat.rhn.common.messaging.SmtpMail.java
/** {@inheritDoc} */ public void setFrom(String from) { try {/*from w w w . j a va 2 s. com*/ message.setFrom(new InternetAddress(from)); } catch (AddressException me) { String msg = "Malformed address in traceback configuration: " + from; log.warn(msg); throw new JavaMailException(msg, me); } catch (MessagingException me) { String msg = "MessagingException while trying to send email: " + me.toString(); log.warn(msg); throw new JavaMailException(msg, me); } }
From source file:com.redhat.rhn.common.messaging.SmtpMail.java
/** * Create a mailer.//w ww .ja v a 2s . c o m */ public SmtpMail() { log.debug("Constructed new SmtpMail."); disallowedDomains = Config.get().getStringArray("web.disallowed_mail_domains"); restrictedDomains = Config.get().getStringArray("web.restrict_mail_domains"); Config c = Config.get(); smtpHost = c.getString(ConfigDefaults.WEB_SMTP_SERVER, "localhost"); String from = c.getString(ConfigDefaults.WEB_DEFAULT_MAIL_FROM); // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", smtpHost); // Get session Session session = Session.getDefaultInstance(props, null); try { message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); } catch (AddressException me) { String msg = "Malformed address in traceback configuration: " + from; log.warn(msg); throw new JavaMailException(msg, me); } catch (MessagingException me) { String msg = "MessagingException while trying to send email: " + me.toString(); log.warn(msg); throw new JavaMailException(msg, me); } }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server// ww w . j ava 2s .c om * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static ErrorType sendMsg(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, final String port, final String security, final File fileAttachment) { String userName = uName; String password = pWord; if (StringUtils.isEmpty(toEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR"); return ErrorType.Error; } if (StringUtils.isEmpty(fromEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR"); return ErrorType.Error; } //if (isGmailEmail()) //{ // return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment); //} Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); boolean isSSL = security.equals("SSL"); String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable", "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback", "mail.imap.auth.plain.disable", }; Properties props = System.getProperties(); for (String key : keys) { props.remove(key); } props.put("mail.smtp.host", host); //$NON-NLS-1$ if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) { props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$ } else { props.remove("mail.smtp.port"); } if (StringUtils.isNotEmpty(security)) { if (security.equals("TLS")) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (isSSL) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.imap.auth.plain.disable", "true"); } } Session session = null; if (isSSL) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uName, pWord); } }); } else { session = Session.getInstance(props, null); } session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ log.debug("Port: " + port); //$NON-NLS-1$ log.debug("Security: " + security); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { try { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } catch (javax.mail.internet.AddressException ex) { UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr); return ErrorType.Error; } } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } final int TRIES = 1; // set the Date: header msg.setSentDate(new Date()); Exception exception = null; // send the message int cnt = 0; do { cnt++; SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { if (isSSL) { Transport.send(msg); } else { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); } fail = false; } catch (SendFailedException mex) { mex.printStackTrace(); exception = mex; } catch (MessagingException mex) { if (mex.getCause() instanceof UnknownHostException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host); } else if (mex.getCause() instanceof ConnectException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError( "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port); } else { mex.printStackTrace(); exception = mex; } } catch (Exception mex) { mex.printStackTrace(); exception = mex; } finally { if (t != null) { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } if (exception != null) { fail = true; instance.lastErrorMsg = exception.toString(); //wrong username or password, get new one if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName); userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) { //the user is done instance.lastErrorMsg = null; return ErrorType.Cancel; } userName = userAndPass.get(0); password = userAndPass.get(1); } } exception = null; } while (fail && cnt < TRIES); } catch (Exception mex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); mex.printStackTrace(); Exception ex = null; if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return ErrorType.Error; } if (fail) { return ErrorType.Error; } //else return ErrorType.OK; }
From source file:org.etudes.component.app.jforum.JForumPrivateMessageServiceImpl.java
/** * Sends private message/*from w w w. j a v a2 s . co m*/ * * @param privateMessage Private message * * @param toUser To user */ protected void sendPrivateMessageEmail(PrivateMessage privateMessage) { if ((privateMessage == null) || (privateMessage.getToUser() == null)) { return; } // send email if to users opted to receive private message email's or high priority private messages if (!privateMessage.getToUser().isNotifyPrivateMessagesEnabled()) { if ((privateMessage.getPriority() != PrivateMessage.PRIORITY_HIGH)) { return; } } if ((privateMessage.getToUser().getEmail() == null) || (privateMessage.getToUser().getEmail().trim().length() == 0)) { return; } InternetAddress from = null; InternetAddress[] to = null; try { InternetAddress toUserEmail = new InternetAddress(privateMessage.getToUser().getEmail()); to = new InternetAddress[1]; to[0] = toUserEmail; String fromUserEmail = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; from = new InternetAddress(fromUserEmail); } catch (AddressException e) { if (logger.isWarnEnabled()) logger.warn("sendPrivateMessageEmail(): Private message email notification error : " + e); return; } String subject = privateMessage.getPost().getSubject(); String postText = privateMessage.getPost().getText(); // full URL's for smilies etc if (postText != null && postText.trim().length() > 0) { postText = XrefHelper.fullUrls(postText); } // format message text Map<String, String> params = new HashMap<String, String>(); StringBuilder toUserName = new StringBuilder(); toUserName.append( privateMessage.getToUser().getFirstName() != null ? privateMessage.getToUser().getFirstName() : ""); toUserName.append(" "); toUserName.append( privateMessage.getToUser().getLastName() != null ? privateMessage.getToUser().getLastName() : ""); params.put("pm.to", toUserName.toString()); StringBuilder fromUserName = new StringBuilder(); fromUserName.append( privateMessage.getFromUser().getFirstName() != null ? privateMessage.getFromUser().getFirstName() : ""); fromUserName.append(" "); fromUserName.append( privateMessage.getFromUser().getLastName() != null ? privateMessage.getFromUser().getLastName() : ""); params.put("pm.from", fromUserName.toString()); params.put("pm.subject", subject); params.put("pm.text", postText); StringBuilder emailSubject = new StringBuilder(); try { Site site = siteService.getSite(privateMessage.getContext()); if (!site.isPublished()) { return; } params.put("site.title", site.getTitle()); emailSubject.append("["); emailSubject.append(site.getTitle()); emailSubject.append(" - "); emailSubject.append(PrivateMessage.MAIL_NEW_PM_SUBJECT); emailSubject.append("] "); emailSubject.append(subject); String portalUrl = ServerConfigurationService.getPortalUrl(); params.put("portal.url", portalUrl); //String currToolId = ToolManager.getCurrentPlacement().getId(); //ToolConfiguration toolConfiguration = site.getTool(currToolId); ToolConfiguration toolConfiguration = site.getToolForCommonId("sakai.jforum.tool"); String siteNavUrl = portalUrl + "/" + "site" + "/" + Web.escapeUrl(site.getId()); if (toolConfiguration != null) siteNavUrl = siteNavUrl + "/" + "page" + "/" + toolConfiguration.getPageId(); params.put("site.url", siteNavUrl); } catch (IdUnusedException e) { if (logger.isWarnEnabled()) { logger.warn(e.toString(), e); } } String messageText = EmailUtil.getPrivateMessageText(params); if (messageText != null) { Post post = privateMessage.getPost(); if ((post != null) && (post.hasAttachments())) { //email with attachments jforumEmailExecutorService.notifyUsers(from, to, emailSubject.toString(), messageText, post.getAttachments()); } else { jforumEmailExecutorService.notifyUsers(from, to, emailSubject.toString(), messageText); } } else { Post post = privateMessage.getPost(); if ((post != null) && (post.hasAttachments())) { //email with attachments jforumEmailExecutorService.notifyUsers(from, to, emailSubject.toString(), postText, post.getAttachments()); } else { jforumEmailExecutorService.notifyUsers(from, to, emailSubject.toString(), postText); } } }
From source file:util.Check.java
/** * Checks if a string is a valid email address. * /* w w w .j av a2 s .c om*/ * @param email * @return */ public boolean isEmail(final String email) { boolean check = false; try { final InternetAddress ia = new InternetAddress(); ia.setAddress(email); try { ia.validate(); // throws an error for invalid addresses and null input, but does not catch all errors // we are using apache commons email validator final EmailValidator validator = EmailValidator.getInstance(); check = validator.isValid(email); // EmailValidator is agnostic about valid domain names... // ...we do an additional check final Pattern p = Pattern.compile("@[a-z0-9-]+(\\.[a-z0-9-]+)*\\" + ".([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|" + "org|pro|tel|travel|xxx)$\\b"); // we need to match against lower case for the above regex final Matcher m = p.matcher(email.toLowerCase()); if (!m.find()) { // reset to false, if we do not have a match check = false; } } catch (final AddressException e1) { LOG.info("isEmail: " + email + " " + e1.toString()); } } catch (final Exception e) { LOG.error("isEmail: " + email + " " + e.toString()); } return check; }