List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address) throws AddressException
From source file:SendMime.java
/** Do the work: send the mail to the SMTP server. */ public void doSend() throws IOException, MessagingException { // Create the Session object session = Session.getDefaultInstance(null, null); session.setDebug(true); // Verbose! try {//from ww w . j a v a 2s . co m // create a message mesg = new MimeMessage(session); // From Address - this should come from a Properties... mesg.setFrom(new InternetAddress("nobody@host.domain")); // TO Address InternetAddress toAddress = new InternetAddress(message_recip); mesg.addRecipient(Message.RecipientType.TO, toAddress); // CC Address InternetAddress ccAddress = new InternetAddress(message_cc); mesg.addRecipient(Message.RecipientType.CC, ccAddress); // The Subject mesg.setSubject(message_subject); // Now the message body. Multipart mp = new MimeMultipart(); BodyPart textPart = new MimeBodyPart(); textPart.setText(message_body); // sets type to "text/plain" BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(html_data, "text/html"); // Collect the Parts into the MultiPart mp.addBodyPart(textPart); mp.addBodyPart(pixPart); // Put the MultiPart into the Message mesg.setContent(mp); // Finally, send the message! Transport.send(mesg); } catch (MessagingException ex) { System.err.println(ex); ex.printStackTrace(System.err); } }
From source file:io.kodokojo.service.SmtpEmailSender.java
private static InternetAddress[] convertToInternetAddress(List<String> input) { List<InternetAddress> res = input.stream().map(addr -> { try {// www . j ava2 s . com return new InternetAddress(addr); } catch (AddressException e) { LOGGER.error("Ignoring following address to send mail.'{}'", addr); return null; } }).filter(addr -> addr != null).collect(Collectors.toList()); return res.toArray(new InternetAddress[res.size()]); }
From source file:edu.psu.citeseerx.myciteseer.domain.logic.AccountValidator.java
/** * Email validation//from ww w.j a v a 2s . c om * @param email email to be validated * @param errors Contains any error that might occur */ public void validateEmail(String email, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "EMAIL_REQUIRED", "Email address is required."); if (errors.getAllErrors().size() > 0) { return; } try { new InternetAddress(email); if (!hasNameAndDomain(email)) { errors.rejectValue("email", "VALID_EMAIL_REQUIRED", "Invalid email address"); } } catch (AddressException e) { errors.rejectValue("email", "VALID_EMAIL_REQUIRED", "Invalid email address"); } if (errors.getAllErrors().size() > 0) { return; } try { Account loginAccount = MCSUtils.getLoginAccount(); Account existingAccount = myciteseer.getAccountByEmail(email); if (existingAccount != null) { if ((loginAccount == null) || !loginAccount.getUsername().equals(existingAccount.getUsername())) { errors.rejectValue("email", "EMAIL_UNIQUE_REQUIRED", "This email address is already in use."); } } } catch (Exception e) { /* ignore */ } }
From source file:com.seer.datacruncher.utils.mail.MailService.java
private InternetAddress[] getToAddress(String mailToAddress) { try {//from w w w.ja va 2 s.c om List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); StringBuilder failedMailAddress = new StringBuilder(); String[] addressList = mailToAddress.split(","); InternetAddress interAddr = null; for (String mailTo : addressList) { if (isEmailValid(mailTo)) { interAddr = new InternetAddress(mailTo); toAddress.add(interAddr); } else { if (failedMailAddress.toString().length() > 0) { failedMailAddress.append(","); } failedMailAddress.append(mailTo); } } InternetAddress[] finalToAddressList = new InternetAddress[toAddress.size()]; if (toAddress != null && toAddress.size() > 0) { return toAddress.toArray(finalToAddressList); } else { if (StringUtils.isEmpty(failedMailAddress.toString())) { log.error("Unable to send the mail to [ " + failedMailAddress.toString() + "]"); } throw new Exception("No valid toAddress configured"); } } catch (Exception e) { log.error(e); } return null; }
From source file:cc.kune.core.server.mail.MailServiceDefault.java
@Override public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body, final boolean isHtml, final String... tos) { if (smtpSkip) { return;/*from w w w. ja va2s. c om*/ } // Get session final Session session = Session.getDefaultInstance(props, null); // Define message final MimeMessage message = new MimeMessage(session); for (final String to : tos) { try { message.setFrom(new InternetAddress(from)); // In case we should use utf8 also in address: // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // If additional header should be added // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B")); final String formatedSubject = subject.getString(); message.setSubject(formatedSubject, "utf-8"); final String formatedBody = body.getString(); if (isHtml) { // message.setContent(formatedBody, "text/html"); message.setText(formatedBody, "UTF-8", "html"); } else { message.setText(formatedBody, "UTF-8"); } // Send message Transport.send(message); } catch (final AddressException e) { } catch (final MessagingException e) { final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s", from, subject, to); log.error(error, e); // Better not to throw exceptions because users emails can be wrong... // throw new DefaultException(error, e); } } }
From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { String passwordDesencriptada = Desencriptar(password2); try {//from w ww. j a v a 2 s . c o m // Propiedades de la conexin Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("alfons018pbg@gmail.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + "")); message.setSubject("Asistencia tcnica"); message.setText("\n \n \n Estimado: " + nombre + " " + apellido + "\n El Servicio Tecnico de SEA ha recibido tu solicitud. " + "\n Los siguientes son tus datos para acceder:" + "\n Correo: " + corre + "\n Password: " + passwordDesencriptada + ""); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("alfons018pbg@gmail.com", "al12fo05zo1990"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:fr.treeptik.cloudunit.utils.EmailUtils.java
/** * Store general propreties (mailJet), create session and addressFrom * * @param mapConfigEmail//from w w w . j a v a 2 s .co m * @return * @throws AddressException * @throws MessagingException */ private Map<String, Object> initEmailConfig(Map<String, Object> mapConfigEmail) throws AddressException, MessagingException { Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading(this.getClass(), "/fr.treeptik.cloudunit.templates/"); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.socketFactory.port", socketFactoryPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", smtpPort); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(apiKey, secretKey); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailFrom)); mapConfigEmail.put("message", message); mapConfigEmail.put("configuration", configuration); return mapConfigEmail; }
From source file:mitm.application.djigzo.james.matchers.MailAddressMatcherTest.java
@Test public void mailAddressMatcherNoRetry() throws Exception { final int retries = 0; final MutableInt count = new MutableInt(); MailAddressMatcher.HasMatchEventHandler handler = new MailAddressMatcher.HasMatchEventHandler() { @Override/*from ww w . j a v a 2 s .c o m*/ public boolean hasMatch(User user) throws MessagingException { count.increment(); throw new ConstraintViolationException("Dummy ConstraintViolationException", null, ""); } }; MailAddressMatcher matcher = new MailAddressMatcher(sessionManager, userWorkflow, actionExecutor, handler, retries); Collection<MailAddress> recipients = MailAddressUtils .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com")); try { matcher.getMatchingMailAddresses(recipients); fail(); } catch (MessagingException e) { /* * Must be caused by ConstraintViolationException */ assertTrue(ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException); } assertEquals(1, count.intValue()); }
From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java
@Override protected void executeImpl(Action action, NodeRef nodeRef) { try {/*from w w w .jav a2 s.c o m*/ MimeMessage mimeMessage = mailService.createMimeMessage(); mimeMessage.setFrom(new InternetAddress((String) action.getParameterValue(PARAM_FROM))); if (action.getParameterValue(PARAM_BCC) != null) { mimeMessage.setRecipients(Message.RecipientType.BCC, (String) action.getParameterValue(PARAM_BCC)); } mimeMessage.setRecipients(Message.RecipientType.TO, (String) action.getParameterValue(PARAM_TO)); mimeMessage.setSubject((String) action.getParameterValue(PARAM_SUBJECT)); mimeMessage.setHeader("Content-Transfer-Encoding", "text/html; charset=UTF-8"); addAttachments(action, nodeRef, mimeMessage); mailService.send(mimeMessage); logger.info("success!"); } catch (AddressException ex) { logger.error("There was an error processing the email address for the mail documents action"); logger.error(ex); } catch (MessagingException ex) { logger.error("There was an error processing the email for the mail documents action"); logger.error(ex); } catch (MailException ex) { logger.error("There was an error processing the action"); logger.error(ex); } }
From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java
/** * @param runner/*w w w . j a va2 s. c om*/ * @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); }