private static Message buildMessage(Session session, String from, String recipients, String subject, String text, String filename) throws MessagingException, AddressException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); message.setSubject(subject); BodyPart messageTextPart = new MimeBodyPart(); messageTextPart.setText(text); BodyPart messageAttachmentPart = new MimeBodyPart(); DataSource source = new FileDataSource(new File(filename)); messageAttachmentPart.setDataHandler(new DataHandler(source)); messageAttachmentPart.setFileName(filename); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageTextPart); multipart.addBodyPart(messageAttachmentPart); message.setContent(multipart); return message; }
public static MimeMessage createMimeMessageWithHtml(Session session) throws MessagingException, AddressException { MimeMessage message = createMimeMessage(session); Multipart multiPart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("text"); multiPart.addBodyPart(textPart); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<b>html</b>", MailContentType.TEXT_HTML.getType()); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); return message; }
/** * * @param tos address String array * @return Address Array * @throws AddressException address convert exception */ protected Address[] toAddresses(final String tos) throws AddressException { if(tos != null && !"".equals(tos)) { final List<Address> to = Lists.newArrayList(); final String[] toArray = tos.split(";"); if(ArrayUtils.isNotEmpty(toArray)) { for(final String address : toArray) { if(StringUtils.isNotBlank(address)) { to.add(new InternetAddress(address.trim())); } } } return to.toArray(new InternetAddress[0]); } return null; }
private void dispatchAnonymousMessage() throws AddressException, MessagingException { int sendDelay = this.config.getInt(ConfigKeys.MAIL_SMTP_DELAY); for (User user : this.users) { if (StringUtils.isEmpty(user.getEmail())) { continue; } if (this.needCustomization) { this.defineUserMessage(user); } Address address = new InternetAddress(user.getEmail()); if (logger.isTraceEnabled()) { logger.trace("Sending mail to: " + user.getEmail()); } this.message.setRecipient(Message.RecipientType.TO, address); Transport.send(this.message, new Address[] { address }); if (sendDelay > 0) { this.waitUntilNextMessage(sendDelay); } } }
private void sendEmail(TokenStoreEntity token, UserEntity user) { Map<String, Object> params = new HashMap<>(); String subject; String template; if (TokenStoreType.USER_ACTIVATION.equals(token.getType())){ params.put("activationUrl", baseUrl + "/registration/activate?at=" + token.getToken()); subject = "Registration Confirmation"; template = "email/registration.html"; } else { params.put("changepassUrl", baseUrl + "/changepass/update?rt=" + token.getToken()); subject = "Reset Password Confirmation"; template = "email/changepass.html"; } try { emailService.sendEmail(null, new InternetAddress(user.getEmail()), subject, params, template); } catch (AddressException e) { throw new RegistrationException("Unable to send activation link"); } }
/** * This method is used to send slack and email notification. * * @param empSlackId slackId of employee * @param channelId channelId of Channel * @param Visitor visitor information * @param ndaFilePath path of nda file * * @return boolean * @throws IOException * @throws AddressException */ public boolean notify(String empSlackId, String channelId, Visitor visitor, String ndaFilePath) throws AddressException, IOException { logger.info("Started sending slack/email notification."); Employee employee = null; SlackChannel channel = null; String locationName = locationService.getLocationName(visitor.getLocation()).getLocationName(); if (StringUtils.isNotBlank(empSlackId) && StringUtils.isBlank(channelId)) { employee = employeeService.getBySlackId(empSlackId); } else { channel = channelService.findByChannelId(channelId); } if (Objects.nonNull(visitor)) { notifyOnSlack(employee, visitor, channel, locationName); notifyOnEmail(employee, visitor, channel, ndaFilePath, locationName); } return true; }
public MailAddress(String str) throws AddressException { InternetAddress address = new InternetAddress(str); email = address.getAddress(); name = address.getPersonal(); String[] strs = email.split("@"); user = strs[0]; if (strs.length>1) { host = strs[1]; } else { host = "localhost"; } }
public void validateEmailList(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (value == null) return; try { _getEmailList(value.toString()); } catch (AddressException ae) { throw new ValidatorException( MessageUtils.getErrorMessage(context, "EMAIL_LIST_ERROR", new Object[]{ae.getRef()})); } }
static private List<InternetAddress> _getEmailList(String values) throws AddressException { ArrayList<InternetAddress> list = new ArrayList<InternetAddress>(); StringTokenizer tokens = new StringTokenizer(values.toString(), ","); while (tokens.hasMoreTokens()) { String token = tokens.nextToken().trim(); InternetAddress address = new InternetAddress(token); // JavaMail 1.3 API: //InternetAddress address = new InternetAddress(token, false); //address.validate(); list.add(address); } return list; }
@Override public List<String> parseAddresses(String emails) throws AddressException { String[] emailsList = new String[0]; String rawEmail = emails; if( rawEmail != null ) { rawEmail = rawEmail.replaceAll(";", " "); emailsList = rawEmail.split("\\s+"); } List<String> addresses = new ArrayList<String>(); for( String email : emailsList ) { new InternetAddress(email).validate(); addresses.add(email); } return addresses; }
/** * Adds a user email address (InternetAddress) to the list * @param userID * @param list * @throws AddressException */ private void addUser(final Integer userID, final List list) throws AddressException { if (userID == null) { return; } final User user = SecurityManager.getInstance().getUser(userID.intValue()); if (user == null) { return; } final String startedEmail = user.getEmail(); if (StringUtils.isBlank(startedEmail)) { return; } list.add(new InternetAddress(startedEmail)); }
/** * Makes InternetAddress from admin system properties. * * @return InternetAddress build admin address */ public static InternetAddress getSystemAdminAddress() throws AddressException { try { final SystemConfigurationManager systemCM = SystemConfigurationManagerFactory.getManager(); final String emailProp = systemCM.getSystemPropertyValue(SystemProperty.BUILD_ADMIN_EMAIL, null); if (StringUtils.isBlank(emailProp)) { throw new AddressException("Build administrator e-mail is not set"); } final String nameProp = systemCM.getSystemPropertyValue(SystemProperty.BUILD_ADMIN_NAME, emailProp); return new InternetAddress(emailProp, nameProp); } catch (UnsupportedEncodingException e) { final AddressException ae = new AddressException(StringUtils.toString(e)); e.initCause(e); throw ae; } }
/** * Returns a list of emails of admin users. * * @param addSystemAdminAddress tru if system admin should be added * @return list of emails of admin users. * @throws AddressException * @throws UnsupportedEncodingException */ public static Collection getAdminAddresslList(final boolean addSystemAdminAddress) throws AddressException { try { // Add system admin email final List result = new ArrayList(11); if (addSystemAdminAddress) { result.add(getSystemAdminAddress()); } // Add all enabled admin users emails final List adminUsers = SecurityManager.getInstance().getAdminUsers(); for (int i = 0; i < adminUsers.size(); i++) { final User user = (User) adminUsers.get(i); result.add(new InternetAddress(user.getEmail(), user.getFullName())); } return result; } catch (UnsupportedEncodingException e) { final AddressException ae = new AddressException(StringUtils.toString(e)); ae.initCause(e); throw ae; } }
/** * Returns String list of addresses. */ private Collection makeReceiverList(final BuildRun buildRun, final int imType, final String imMessageSelection, final boolean applyStartFilter, final boolean applyFirstStepStartFilter, final boolean applyLastStepResultFilter, final byte watchLevel) throws AddressException { // get users having imType as IM final Map imUsersMap = cm.getIMUsersEmailMap(imType, imMessageSelection); // Createc composer final EmailRecipientListComposer composer = new EmailRecipientListComposer(); composer.setCaseSensitiveUserName(NotificationUtils.isCaseSensitiveUserName(buildRun.getBuildID())); // Get recipients final EmailRecipients recipients = composer.makeRecipients(buildRun, vcsUserMap, applyStartFilter, applyFirstStepStartFilter, applyLastStepResultFilter, true, watchLevel); // filter users identified by this list of e-mail recipients to a list of IM receivers. final Map result = new HashMap(23); for (final Iterator i = recipients.getAllAddresses().iterator(); i.hasNext();) { final String imAddress = (String) imUsersMap.get(((InternetAddress) i.next()).getAddress().toLowerCase()); if (imAddress != null) { result.put(imAddress, Boolean.TRUE); } } return new ArrayList(result.keySet()); }
/** */ public void test_cr936_firstStepIsConsidered() throws AddressException { final BuildRun buildRun = cm.getBuildRun(3); // set to send only to the first start final BuildConfigAttribute bca = new BuildConfigAttribute(buildRun.getBuildID(), BuildConfigAttribute.SEND_START_NOTICE_FOR_FIRST_STEP_ONLY, BuildConfigAttribute.OPTION_CHECKED); cm.saveObject(bca); composer.addSourceControlUser("test2"); // says filter is ignored EmailRecipients emailRecipients = composer.makeRecipients(buildRun, Collections.EMPTY_MAP, false, false, false, true, BuildWatcher.LEVEL_BROKEN); assertEquals(3, emailRecipients.getAllAddresses().size()); // says filter is considered emailRecipients = composer.makeRecipients(buildRun, Collections.EMPTY_MAP, false, true, false, true, BuildWatcher.LEVEL_BROKEN); assertEquals(0, emailRecipients.getAllAddresses().size()); }
public static void sendMail(String host, int port, String username, String password, String recipients, String subject, String content, String from) throws AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); message.setSubject(subject); message.setText(content); Transport.send(message); }
public void sendMail(String host, String from, String to, String subject, String messageText) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); msg.setSubject(subject); msg.setText(messageText); Transport.send(msg); } catch (AddressException ae) { ae.printStackTrace(System.out); } catch (MessagingException me) { me.printStackTrace(System.out); } }
private Message createMessage(final String emailAddress, final String subjectLine, final Session session, final MimeMultipart mimeMultipart, final ExtensionProperties properties) throws MessagingException { final List<InternetAddress> addresses = new ArrayList<>(); try { addresses.add(new InternetAddress(emailAddress)); } catch (final AddressException e) { log.warn(String.format("Could not create the address from %s: %s", emailAddress, e.getMessage())); } if (addresses.isEmpty()) { throw new RuntimeException("There were no valid email addresses supplied."); } final Message message = new MimeMessage(session); message.setContent(mimeMultipart); message.setFrom(new InternetAddress(properties.getEmailFromAddress())); message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()])); message.setSubject(subjectLine); return message; }
@Test public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() { MockJavaMailSender sender = new MockJavaMailSender(); MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.setFrom(new InternetAddress("")); } }; try { sender.send(preparator); } catch (MailParseException ex) { // expected assertTrue(ex.getCause() instanceof AddressException); } }
/** * Validates the user input to ensure that it is a valid email address. * * @param input the String input, always a non-null non-empty String * @param targetType realistically always String since java.lang.String is final * @param errors a non-null collection of errors to populate in case of error * @return the parsed address, or null if there are no errors. Note that the parsed address * may be different from the input if extraneous characters were removed. */ public String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors) { String result = null; try { InternetAddress address = new InternetAddress(input, true); result = address.getAddress(); if (!result.contains("@")) { result = null; throw new AddressException(); } } catch (AddressException ae) { errors.add( new ScopedLocalizableError("converter.email", "invalidEmail") ); } return result; }
public static MimeMessage createMimeMessageWithAttachment(Session session, File attachment) throws MessagingException, AddressException, IOException { MimeMessage message = createMimeMessage(session); Multipart multiPart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("text"); multiPart.addBodyPart(textPart); MimeBodyPart filePart = new MimeBodyPart(); filePart.attachFile(attachment); multiPart.addBodyPart(filePart); message.setContent(multiPart); return message; }
@Override public Boolean isValid() { try { InternetAddress internetAddress = new InternetAddress(email); internetAddress.validate(); return (name != null && !name.isEmpty()) && (surname != null && !surname.isEmpty()) && (phone != null && !phone.isEmpty()) && (email != null && !email.isEmpty()) && (password != null && !password.isEmpty()) && (passwordConfirmation != null && !passwordConfirmation.isEmpty()); } catch (AddressException e) { return Boolean.FALSE; } }
@RequestMapping(value = "/receive", method = RequestMethod.POST) public String receive( @RequestBody EmailToSend emailToSend) throws AddressException { for (Recipient recipient : emailToSend.getRecipients()) { String emailMessage = emailToSend.getHtml(); if (recipient.getCustomProperties().size() > 0) { for (Object o : recipient.getCustomProperties().entrySet()) { Map.Entry pair = (Map.Entry) o; emailMessage = StringUtils.replace(emailMessage, TOKEN_SEPARATOR + pair.getKey() + TOKEN_SEPARATOR, (String) pair.getValue()); } } EmailJmsMessage emailJmsMessage = new EmailJmsMessage(emailMessage, emailToSend.getAttachments(), emailToSend.getSubject(), new InternetAddress(recipient.getEmailAddress())); sendJmsMessage(emailJmsMessage); } return "E-Mail request stored"; }
@Test public void testInternetAddress() throws URISyntaxException, IOException, AddressException { final Fuzzer rfc2822 = new Fuzzer( InternetAddressTest.class.getResourceAsStream("/rfc2822.txt")); final Fuzzer rfc1034 = new Fuzzer( InternetAddressTest.class.getResourceAsStream("/rfc1034.txt")); for (int i = 0; i < 1000; i++) { final String localPart = rfc2822.generateAscii("local-part", EXCLUDE_2822); final String domain = rfc1034.generateAscii("domain").trim(); if (domain.isEmpty()) { // legal but not supported continue; } final InternetAddress addr = new InternetAddress( localPart + "@" + domain, true); addr.validate(); } }
/** * Send a Test Mail to check configuration * @throws AddressException If mail address is wrong * @throws MessagingException If building MimeMessage fails */ public synchronized void sendTestMail() throws AddressException, MessagingException { String to = getToAddress(); String from = getFromAddress(); String subject = "Testing mail-addresses"; String smtpHost = getSmtpHost(); String attText = "JMeter-Testmail" + "\n" + "To: " + to + "\n" + "From: " + from + "\n" + "Via: " + smtpHost + "\n" + "Fail Subject: " + getFailureSubject() + "\n" + "Success Subject: " + getSuccessSubject(); log.info(attText); sendMail(from, getAddressList(), subject, attText, smtpHost, getSmtpPort(), getLogin(), getPassword(), getMailAuthType(), true); log.info("Test mail sent successfully!!"); }
public MailSender() throws FileNotFoundException, UnknownHostException, AddressException { ModelInJar.loadProperties(); // Reads result.mail.address and so on. final String mailto = System.getProperty(MAIL_ADDRESS); if (mailto != null) { this.toAddresses = InternetAddress.parse(mailto); this.from = new InternetAddress("TLC - The friendly model checker <" + toAddresses[0].getAddress() + ">"); this.fromAlt = new InternetAddress("TLC - The friendly model checker <" + System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName() + ">"); // Record/Log output to later send it by email final String tmpdir = System.getProperty("java.io.tmpdir"); this.out = new File(tmpdir + File.separator + "MC.out"); ToolIO.out = new LogPrintStream(out); this.err = new File(tmpdir + File.separator + "MC.err"); ToolIO.err = new LogPrintStream(err); } }
/** * 发送邮件 * * @param recipient 收件人邮箱地址 * @param subject 邮件主题 * @param content 邮件内容 * @throws AddressException * @throws MessagingException */ public void send(String recipient, String subject, Object content) throws AddressException, MessagingException { // 创建mime类型邮件 final MimeMessage message = new MimeMessage(session); // 设置发信人 message.setFrom(new InternetAddress(authenticator.getUsername())); // 设置收件人 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipient)); // 设置主题 message.setSubject(subject); message.setSentDate(new Date()); // 设置邮件内容 message.setContent(content.toString(), "text/html;charset=utf-8"); // 发送 Transport.send(message); }
/** * 群发邮件 * * @param recipients 收件人们 * @param subject 主题 * @param content 内容 * @throws AddressException * @throws MessagingException */ public void send(List<String> recipients, String subject, Object content) throws AddressException, MessagingException { // 创建mime类型邮件 final MimeMessage message = new MimeMessage(session); // 设置发信人 message.setFrom(new InternetAddress(authenticator.getUsername())); message.setSentDate(new Date()); // 设置收件人们 final int num = recipients.size(); InternetAddress[] addresses = new InternetAddress[num]; for (int i = 0; i < num; i++) { addresses[i] = new InternetAddress(recipients.get(i)); } message.setRecipients(MimeMessage.RecipientType.TO, addresses); // 设置主题 message.setSubject(subject); // 设置邮件内容 message.setContent(content.toString(), "text/html;charset=utf-8"); // 发送 Transport.send(message); }
public void validateUserMail(String userMail) throws BadRequestException { if (userMail == null || userMail.isEmpty()) { throw new BadRequestException("User mail can't be null or ''"); } try { InternetAddress address = new InternetAddress(userMail); address.validate(); } catch (AddressException e) { throw new BadRequestException( "E-Mail validation failed. Please check the format of your e-mail address."); } // Check blacklist for (String current : emailBlackList) { if ((current.startsWith("*") && userMail.endsWith(current.substring(1))) || userMail.equals(current)) { throw new BadRequestException("User mail " + userMail + " is forbidden."); } } }
public MimeMessage createEmailMessageWithImage(String to, String subject, String body, String imgFileName) throws AddressException, MessagingException { MimeMessage msg = createEmailMessage(to, subject, String.format("%s <br/>\n <img src=\"%s\"/>", body, imgFileName)); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(String.format("%s <br/>\n <img src=\"%s\"/>", body, imgFileName), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); File img = new File(imgFileName); DataSource source = new FileDataSource(img); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(imgFileName); messageBodyPart.setDisposition(Part.INLINE); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); return msg; }
/** * Group addresses by type * * @param mailPO * @return */ private static Map<MailAddressType, List<InternetAddress>> getGroupedAddresses(MailPO mailPO) { Map<MailAddressType, List<InternetAddress>> result = new HashMap<>(); for (MailReceiverPO receiverPO : mailPO.getReceivers()) { MailAddressType type = MailAddressType.getBy(receiverPO.getType()); List<InternetAddress> someType = result.get(type); if (someType == null) { someType = new ArrayList<>(); result.put(type, someType); } try { someType.add(new InternetAddress(receiverPO.getAddress())); } catch(AddressException exception) { throw new RuntimeException(exception); } } return result; }
public Address[] getAllRecipients() { Address[] address = null; Optional<String[]> optional = Optional.ofNullable(recipients); if (optional.isPresent()) { address = Arrays.stream(optional.get()).map(s -> { InternetAddress internetAddress = null; try { internetAddress = new InternetAddress(s); } catch (AddressException e) { } return internetAddress; }).toArray(InternetAddress[]::new); } return address; }