javax.mail.internet.AddressException Java Examples

The following examples show how to use javax.mail.internet.AddressException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EndUserServiceImpl.java    From omh-dsu-ri with Apache License 2.0 7 votes vote down vote up
@Override
@Transactional
public void registerUser(EndUserRegistrationData registrationData) {

    if (doesUserExist(registrationData.getUsername())) {
        throw new EndUserRegistrationException(registrationData);
    }

    EndUser endUser = new EndUser();
    endUser.setUsername(registrationData.getUsername());
    endUser.setPasswordHash(passwordEncoder.encode(registrationData.getPassword()));
    endUser.setRegistrationTimestamp(OffsetDateTime.now());

    if (registrationData.getEmailAddress() != null) {
        try {
            endUser.setEmailAddress(new InternetAddress(registrationData.getEmailAddress()));
        }
        catch (AddressException e) {
            throw new EndUserRegistrationException(registrationData, e);
        }
    }

    endUserRepository.save(endUser);
}
 
Example #2
Source File: ContactListTest.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void testConversionToEmailAddressFormatsDoesNotFailWithoutEmailsAddedAndInstitutionalPrioTrue() throws AddressException {
    // Setup
    String simple = "Simple Name With Spaces";
    ContactList contactlist = new ContactList(simple);
    contactlist.setEmailPrioInstitutional(true);
    // exercise
    contactlist.getEmailsAsAddresses();
    contactlist.getEmailsAsStrings();
    contactlist.getIdentityEmails();
    contactlist.getRFC2822NameWithAddresses();
    // verify all different email conversion and formatting of valid addresses
    verifyNameAndRFC2822NameFor(simple, contactlist);

    assertTrue("Institutional Email is set", contactlist.isEmailPrioInstitutional());
}
 
Example #3
Source File: App.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
@Override
public void run() {
    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    Warehouse warehouse = Warehouses.newDbWarehouse(clientId);

    List<ReportDelivery> reportDeliveries;
    try {
        reportDeliveries = createReportDeliveries(clientId);
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    new Web(arguments, dependencyFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, dependencyFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example #4
Source File: App.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
@Override
public void run() {
    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    Warehouse warehouse = Warehouses.newDbWarehouse(clientId);

    List<ReportDelivery> reportDeliveries;
    try {
        reportDeliveries = createReportDeliveries(clientId);
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    new Web(arguments, dependencyFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, dependencyFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example #5
Source File: MailSender.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("null")
private InternetAddress[] parseAddresses(String addressesStr) throws AddressException {
    if (addressesStr == null) {
        throw new AddressException("Address is not assigned.");
    }

    String[] addresses = addressesStr.trim().split(";|,");
    if ((addresses == null) || (addresses.length == 0)) {
        new AddressException("Address is missing.");
    }

    List<InternetAddress> resultList = new ArrayList<InternetAddress>(addresses.length);
    for (int i = 0; i < addresses.length; i++) {
        String address = addresses[i].trim();
        if (address.length() > 0) {
            resultList.add(new InternetAddress(address));
        }
    }

    if (resultList.size() == 0) {
        new AddressException("Address is missing; result list is empty.");
    }

    return resultList.toArray(new InternetAddress[resultList.size()]);
}
 
Example #6
Source File: CreateUserCommand.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Private helper method to validate the user's email address. Puts errors into the
 * errors list.
 */
private void validateEmail() {
    // Make sure user and email are not null
    if (user == null || user.getEmail() == null) {
        errors.add(new ValidatorError("error.addr_invalid", "null"));
        return;
    }

    // Make email is not over the max length
    if (user.getEmail().length() > UserDefaults.get().getMaxEmailLength()) {
        errors.add(new ValidatorError("error.maxemail"));
        return;
    }

    // Make sure set email is valid
    try {
        new InternetAddress(user.getEmail()).validate();
    }
    catch (AddressException e) {
        errors.add(new ValidatorError("error.addr_invalid", user.getEmail()));
    }
}
 
Example #7
Source File: CorruptEmailFixer.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
private boolean hasValidFrom(JavaxMailMessage message) {
  String[] fromHeaders = message.getHeader("From");
  Preconditions.checkState(fromHeaders.length == 1,
      "Expected exactly 1 From header, got: " + Arrays.toString(fromHeaders));
  String rawAddress = fromHeaders[0].replaceAll("\\s+"," ");
  try {
    InternetAddress[] address =
        InternetAddress.parseHeader(rawAddress, true);
    Preconditions.checkState(address.length == 1,
        "Expected exactly 1 From address, got: " + Arrays.toString(address));
    System.err.format("Valid? %s == %s\n", address[0].toString(), rawAddress);
    return address[0].toString().equals(rawAddress);
  } catch (AddressException e) {
    System.err.format("Not valid from because: %s", e.getMessage());
    return false;
  }
}
 
Example #8
Source File: EmailUtils.java    From subethasmtp with Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the string is a valid email address
 */
public static boolean isValidEmailAddress(String address)
{
	// MAIL FROM: <>
	if (address.length() == 0)
		return true;

	boolean result = false;
	try
	{
		InternetAddress[] ia = InternetAddress.parse(address, true);
		if (ia.length == 0)
			result = false;
		else
			result = true;
	}
	catch (AddressException ae)
	{
		result = false;
	}
	return result;
}
 
Example #9
Source File: StringUtils.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the string passed in is a valid Email address.
 *
 * @param address Email address to test for validity.
 * @return true if the string passed in is a valid email address.
 */
public static boolean isValidEmailAddress(String address) {
    if (address == null) {
        return false;
    }

    if (!address.contains("@")) {
        return false;
    }

    try {
        InternetAddress.parse(address);
        return true;
    }
    catch (AddressException e) {
        return false;
    }
}
 
Example #10
Source File: EmailerTest.java    From olat with Apache License 2.0 6 votes vote down vote up
private void caputureAndVerifyValuesForCreateMessage(List<ContactList> expectedRecipients, String expectedSubject, String expectedBody, List<File> expectedAttachments) throws AddressException, MessagingException {
	verify(webappAndMailhelperMockSystemMailer, times(1)).createMessage(fromCaptor.capture(), contactListCaptor.capture(), bodyCaptor.capture(), subjectCaptor.capture(), attachmentsCaptor.capture(), resultCaptor.capture());
	InternetAddress capturedFrom = fromCaptor.getValue();
	assertEquals("is olat admin email", ObjectMother.OLATADMIN_EMAIL, capturedFrom.getAddress());
	assertEquals("Emails in xyz are correct", expectedRecipients, contactListCaptor.getValue());
	assertEquals("subject", expectedSubject, subjectCaptor.getValue()); 
	assertEquals("body!", expectedBody, bodyCaptor.getValue());
	
	//this is Duplication of code inside Emailer, how to avoid?
	if(expectedAttachments == null || expectedAttachments.isEmpty()){
		assertArrayEquals("null attachements", null, attachmentsCaptor.getValue());
	}else{
		File[] tmp = new File[SIZE];
		assertArrayEquals("compare as arrays", expectedAttachments.toArray(tmp), attachmentsCaptor.getValue());
	}		
}
 
Example #11
Source File: MailerWithTemplate.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Helper: creates an address array from a list of identities
 * 
 * @param recipients
 * @param result
 * @return Address array
 */
private Address[] createAddressesFromIdentities(List<? extends OLATPrincipal> recipients, MailerResult result) {
    Address[] addresses = null;
    if (recipients != null && recipients.size() > 0) {
        List<Address> validRecipients = new ArrayList<Address>();
        for (int i = 0; i < recipients.size(); i++) {
            OLATPrincipal principal = recipients.get(i);
            try {
                validRecipients.add(new InternetAddress(principal.getAttributes().getEmail()));
            } catch (AddressException e) {
                result.addFailedIdentites(principal);
            }
        }
        addresses = validRecipients.toArray(new Address[validRecipients.size()]);
    }
    return addresses;
}
 
Example #12
Source File: ForgotPassword.java    From ShoppingCartinJava with MIT License 5 votes vote down vote up
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);

    // -- Create a new message --
    final MimeMessage msg = new MimeMessage(session);

    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());      
    t.close();
}
 
Example #13
Source File: DownloadEmailUtils.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * Transforms a iterable of string into a list of email addresses.
 */
private static List<Address> toInternetAddresses(Iterable<String> strEmails) {
  List<Address> emails = Lists.newArrayList();
  for (String address : strEmails) {
    try {
      emails.add(new InternetAddress(address));
    } catch (AddressException e) {
      // bad address?
      LOG.warn("Ignore corrupt email address {}", address);
    }
  }
  return emails;
}
 
Example #14
Source File: MailTestUtil.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
public static MimeMessage createMimeMessage(Session session) throws MessagingException, AddressException {
  MimeMessage message = new MimeMessage(session);

  message.setFrom(new InternetAddress("[email protected]"));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
  message.setSubject("subject");

  return message;
}
 
Example #15
Source File: SMTPAppenderBase.java    From lemon with Apache License 2.0 5 votes vote down vote up
InternetAddress getAddress(String addressStr) {
    try {
        return new InternetAddress(addressStr);
    } catch (AddressException e) {
        addError("Could not parse address [" + addressStr + "].", e);

        return null;
    }
}
 
Example #16
Source File: ImapConnection.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
protected void appendMailEnvelopeHeader(StringBuilder buffer, String[] value) {
    buffer.append(' ');
    if (value != null && value.length > 0) {
        try {
            String unfoldedValue = MimeUtility.unfold(value[0]);
            InternetAddress[] addresses = InternetAddress.parseHeader(unfoldedValue, false);
            if (addresses.length > 0) {
                buffer.append('(');
                for (InternetAddress address : addresses) {
                    buffer.append('(');
                    String personal = address.getPersonal();
                    if (personal != null) {
                        appendEnvelopeHeaderValue(buffer, personal);
                    } else {
                        buffer.append("NIL");
                    }
                    buffer.append(" NIL ");
                    String mail = address.getAddress();
                    int atIndex = mail.indexOf('@');
                    if (atIndex >= 0) {
                        buffer.append('"').append(mail, 0, atIndex).append('"');
                        buffer.append(' ');
                        buffer.append('"').append(mail.substring(atIndex + 1)).append('"');
                    } else {
                        buffer.append("NIL NIL");
                    }
                    buffer.append(')');
                }
                buffer.append(')');
            } else {
                buffer.append("NIL");
            }
        } catch (AddressException | UnsupportedEncodingException e) {
            DavGatewayTray.warn(e);
            buffer.append("NIL");
        }
    } else {
        buffer.append("NIL");
    }
}
 
Example #17
Source File: EmailSender.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private List<InternetAddress> toAddress(List<String> emails) throws AddressException {
  List<InternetAddress> list = new ArrayList<>(emails.size());
  for (String email : emails) {
    list.add(toAddress(email));
  }
  return list;
}
 
Example #18
Source File: EMail.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private InternetAddress[] getAddresses(Collection<Recipient> recipients) throws AddressException {
	InternetAddress[] recs = new InternetAddress[recipients.size()];
	Iterator<Recipient> iter = recipients.iterator();
	int i = 0;

	while (iter.hasNext()) {
		Recipient rec = iter.next();
		recs[i] = new InternetAddress(rec.getAddress());
		i++;
	}

	return recs;
}
 
Example #19
Source File: MailAddressTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void testToInternetAddress() throws AddressException {
    InternetAddress b = new InternetAddress(GOOD_ADDRESS);
    MailAddress a = new MailAddress(b);

    assertThat(a.toInternetAddress()).isEqualTo(b);
    assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
 
Example #20
Source File: Main.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery("[email protected]"));
        result.add(new DirectoryReportDelivery("."));
    } else {
        result.add(new DirectoryReportDelivery("."));
    }
    return result;
}
 
Example #21
Source File: Main.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery("[email protected]"));
        result.add(new DirectoryReportDelivery("."));
    } else {
        result.add(new DirectoryReportDelivery("."));
    }
    return result;
}
 
Example #22
Source File: App.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery("[email protected]"));
        result.add(new DirectoryReportDelivery("."));
    } else {
        result.add(new DirectoryReportDelivery("."));
    }
    return result;
}
 
Example #23
Source File: MailAddressCollectionReader.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static Optional<MailAddress> getMailAddress(String s) {
    try {
        if (s.equals(MailAddress.NULL_SENDER_AS_STRING)) {
            return Optional.empty();
        }
        return Optional.of(new MailAddress(s));
    } catch (AddressException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: App.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery(DESTINATION_ADDRESS));
        result.add(new DirectoryReportDelivery(DESTINATION_DIRECTORY));
    } else {
        result.add(new DirectoryReportDelivery(DESTINATION_DIRECTORY));
    }
    return result;
}
 
Example #25
Source File: EmailerTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldSendMailToContactListMembersWithEmptyAttachements() throws AddressException, MessagingException {
	//Setup
	//Exercise
	systemEmailer.sendEmail(recipientsContactLists, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY, emptyAttachmentsMocked);
	//Verify
	verify(webappAndMailhelperMockSystemMailer, times(1)).send(any(MimeMessage.class), any(MailerResult.class));
	caputureAndVerifyValuesForCreateMessage(recipientsContactLists, ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY+ObjectMother.MAIL_TEMPLATE_FOOTER,emptyAttachmentsMocked);
}
 
Example #26
Source File: MailAddress.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an InternetAddress representing the same address
 * as this MailAddress.
 *
 * @return the address
 */
public InternetAddress toInternetAddress() {
    try {
        return new InternetAddress(toString());
    } catch (javax.mail.internet.AddressException ae) {
        //impossible really
        return null;
    }
}
 
Example #27
Source File: Main.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    List<String> arguments = List.of(args);

    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    ProductDao productDao = new MemoryProductDao();
    CustomerDao customerDao = new DbCustomerDao();
    InventoryDao inventoryDao = new MemoryInventoryDao(productDao);
    OrderDao orderDao = new MemoryOrderDao(productDao, customerDao);

    ReportGeneration reportGeneration;
    if (clientId == 1) {
        reportGeneration = new DefaultReportGeneration(orderDao);
    } else if (clientId == 2) {
        reportGeneration = new AlternativeReportGeneration(orderDao);
    } else {
        throw new IllegalStateException("Unknown client ID: " + clientId);
    }

    Warehouse warehouse = new Warehouse(productDao, customerDao, inventoryDao, orderDao, reportGeneration);

    ReportDelivery reportDelivery;
    try {
        reportDelivery = new EmailReportDelivery("[email protected]");
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    new Web(arguments, warehouse, reportDelivery).run();
    new Cli(arguments, warehouse, reportDelivery).run();
    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example #28
Source File: EmailerTest.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * TODO: Emailer does not fail with using empty ContactList, how does javax.mail handle no recipients?
 * @throws AddressException
 * @throws MessagingException
 */
@Test
public void testShouldNotFailWithEmptyContactList() throws AddressException, MessagingException{
	//Setup
	//Exercise
	systemEmailer.sendEmail(new ArrayList<ContactList>(), ObjectMother.AN_EXAMPLE_SUBJECT, ObjectMother.HELLOY_KITTY_THIS_IS_AN_EXAMPLE_BODY);
	//Verify
	verify(webappAndMailhelperMockSystemMailer, times(1)).send(any(MimeMessage.class), any(MailerResult.class));
}
 
Example #29
Source File: JMSCacheableMailQueue.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Populate Mail with values from Message. This exclude the
 * {@link MimeMessage}
 *
 * @param message
 * @throws JMSException
 */
protected MailImpl.Builder populateMail(Message message) throws JMSException {
    String name = message.getStringProperty(JAMES_MAIL_NAME);
    MailImpl.Builder builder = MailImpl.builder().name(name);
    builder.errorMessage(message.getStringProperty(JAMES_MAIL_ERROR_MESSAGE));
    builder.lastUpdated(new Date(message.getLongProperty(JAMES_MAIL_LAST_UPDATED)));

    Optional.ofNullable(SerializationUtil.<PerRecipientHeaders>deserialize(message.getStringProperty(JAMES_MAIL_PER_RECIPIENT_HEADERS)))
            .ifPresent(builder::addAllHeadersForRecipients);

    String recipients = message.getStringProperty(JAMES_MAIL_RECIPIENTS);
    StringTokenizer recipientTokenizer = new StringTokenizer(recipients, JAMES_MAIL_SEPARATOR);
    while (recipientTokenizer.hasMoreTokens()) {
        String token = recipientTokenizer.nextToken();
        try {
            MailAddress rcpt = new MailAddress(token);
            builder.addRecipient(rcpt);
        } catch (AddressException e) {
            // Should never happen as long as the user does not modify the
            // the header by himself
            LOGGER.error("Unable to parse the recipient address {} for builder {}, so we ignore it", token, name, e);
        }
    }
    builder.remoteAddr(message.getStringProperty(JAMES_MAIL_REMOTEADDR));
    builder.remoteHost(message.getStringProperty(JAMES_MAIL_REMOTEHOST));

    String attributeNames = message.getStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES);

    builder.addAttributes(
        splitter.splitToList(attributeNames)
        .stream()
        .flatMap(attributeName -> mailAttribute(message, attributeName))
        .collect(Guavate.toImmutableList()));

    builder.sender(MaybeSender.getMailSender(message.getStringProperty(JAMES_MAIL_SENDER)).asOptional());
    builder.state(message.getStringProperty(JAMES_MAIL_STATE));
    return builder;
}
 
Example #30
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static String sanitizeEmail(String email) {
    if (email.contains("<") && email.contains(">"))
        try {
            InternetAddress address = new InternetAddress(email);
            return address.getAddress();
        } catch (AddressException ignored) {
        }

    return email;
}