类javax.mail.internet.AddressException源码实例Demo

下面列出了怎么用javax.mail.internet.AddressException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: omh-dsu-ri   文件: EndUserServiceImpl.java
@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);
}
 
源代码2 项目: olat   文件: MailerWithTemplate.java
/**
 * 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;
}
 
源代码3 项目: olat   文件: EmailerTest.java
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());
	}		
}
 
源代码4 项目: subethasmtp   文件: EmailUtils.java
/**
 * @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;
}
 
源代码5 项目: spacewalk   文件: CreateUserCommand.java
/**
 * 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()));
    }
}
 
@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);
}
 
@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);
}
 
源代码8 项目: Openfire   文件: StringUtils.java
/**
 * 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;
    }
}
 
源代码9 项目: olat   文件: ContactListTest.java
@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());
}
 
源代码10 项目: mail-importer   文件: CorruptEmailFixer.java
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;
  }
}
 
源代码11 项目: megatron-java   文件: MailSender.java
@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()]);
}
 
源代码12 项目: BIMserver   文件: MailSystem.java
public static boolean isValidEmailAddress(String aEmailAddress) {
	if (aEmailAddress == null) {
		return false;
	}
	try {
		new InternetAddress(aEmailAddress);
		if (!hasNameAndDomain(aEmailAddress)) {
			return false;
		}
	} catch (AddressException ex) {
		return false;
	}
	return true;
}
 
@POST
@Path("/verify")
@RequiresAuthentication
@RequiresPermissions("nexus:settings:update")
public ApiEmailValidation testEmailConfiguration(@NotNull String verificationAddress)
{
  EmailConfiguration emailConfiguration = emailManager.getConfiguration();

  if (emailConfiguration == null) {
    return new ApiEmailValidation(false, "Email Settings are not yet configured");
  }

  try {
    emailManager.sendVerification(emailConfiguration, verificationAddress);
    return new ApiEmailValidation(true);
  }
  catch (EmailException e) {
    log.debug("Unable to send verification", e);
    String exceptionMessage = e.getMessage().replace(e.getCause().getClass().getName() + ": ", "");
    if (e.getCause() instanceof AddressException) {
      throw new WebApplicationMessageException(BAD_REQUEST, '"' + exceptionMessage + '"', APPLICATION_JSON);
    }
    else {
      return new ApiEmailValidation(false, exceptionMessage);
    }
  }
}
 
源代码14 项目: greenmail   文件: RcptCommand.java
@Override
public void execute(SmtpConnection conn, SmtpState state,
                    SmtpManager manager, String commandLine) {
    Matcher m = param.matcher(commandLine);

    try {
        if (m.matches()) {
            if (state.getMessage().getReturnPath() != null) {
                String to = m.group(1);

                MailAddress toAddr = new MailAddress(to);

                String err = manager.checkRecipient(state, toAddr);
                if (err != null) {
                    conn.send(err);

                    return;
                }

                state.getMessage().addRecipient(toAddr);
                conn.send("250 OK");
            } else {
                conn.send("503 MAIL must come before RCPT");
            }
        } else {
            conn.send("501 Required syntax: 'RCPT TO:<[email protected]>'");
        }
    } catch (AddressException e) {
        conn.send("501 Malformed email address. Use form [email protected]");
    }
}
 
源代码15 项目: james-project   文件: MailCmdHandler.java
private MaybeSender toMaybeSender(String senderAsString) throws AddressException {
    if (senderAsString.length() == 0) {
        // This is the <> case.
        return MaybeSender.nullSender();
    }
    if (senderAsString.equals("@")) {
        return MaybeSender.nullSender();
    }
    return MaybeSender.of(new MailAddress(
        appendDefaultDomainIfNeeded(senderAsString)));
}
 
源代码16 项目: openemm   文件: AgnUtils.java
private static InternetAddress asInternetAddress(String address) {
	try {
		return new InternetAddress(address);
	} catch (AddressException e) {
		throw new RuntimeException(e);
	}
}
 
源代码17 项目: gpmall   文件: EmailConfig.java
/**
 * 获得抄送地址
 * @return
 */
public Address[] getCcInternetAddress(){
    Address[] addresses = new Address[]{};
    List<InternetAddress> internetAddressList = new ArrayList<>();
    toAddresss.forEach(toAddress->{
        try {
            internetAddressList.add(new InternetAddress(toAddress));
        } catch (AddressException e) {
            e.printStackTrace();
        }
    });
    return (Address[]) internetAddressList.toArray(addresses);
}
 
@Theory
public void shouldFailWithErrorWithAnyOtherMessagingException(final MessagingException me){
	//setup
	ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
		@Override
		protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
			assertNotNull("emailer was constructed", emailer);
			throw me;
		}
		
		@Override
		protected MailTemplate getMailTemplate() {
			return emptyMailTemplate;
		};
		
		@Override
		protected List<ContactList> getTheToContactLists() {
			return theContactLists;
		}
		
		@Override
		protected Identity getFromIdentity() {
			return theFromIdentity;
		}
	};
	
	//exercise
	MessageSendStatus sendStatus = doSendWithSendFailedException.send();					

	//verify
	assertEquals(MessageSendStatusCode.MAIL_CONTENT_NOK, sendStatus.getStatusCode());
	verifyStatusCodeIndicateMessagingExcpetionOnly(sendStatus);
	verifySendStatusIsWarn(sendStatus);
	assertFalse(sendStatus.canProceedWithWorkflow());
	
}
 
源代码19 项目: james-project   文件: MockMessageHandler.java
private MailAddress parse(String mailAddress) {
    try {
        return new MailAddress(mailAddress);
    } catch (AddressException e) {
        LOGGER.error("Error parsing mail address '{}'", mailAddress, e);
        throw new RejectException(SMTPStatusCode.SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS_501.getRawCode(), "invalid email address supplied");
    }
}
 
源代码20 项目: rice   文件: EmailToList.java
public Address[] getToAddressesAsAddressArray() throws AddressException {
Address[] recipientAddresses = new Address[this.toAddresses.size()];
for (int i = 0; i < recipientAddresses.length; i++) {
    recipientAddresses[i] = new InternetAddress((String) this.toAddresses.get(i));
 }
       return recipientAddresses;
   }
 
源代码21 项目: gocd   文件: ServerConfigService.java
public LocalizedOperationResult validateEmail(String email) {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    try {
        new InternetAddress(email, true);
    } catch (AddressException e) {
        result.notAcceptable("Not a valid email address.");
    }
    return result;
}
 
源代码22 项目: openhab1-addons   文件: PushbulletAPIConnector.java
/**
 * Inner method checking if email address is valid.
 *
 * @param email
 * @return
 */
private static boolean isValidEmail(String email) {
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
        return true;
    } catch (AddressException e) {
        return false;
    }
}
 
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;
}
 
public static void main(String[] args) {
    List<String> arguments = List.of(args);

    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;
    }

    ExporterFactory exporterFactory = FULL_VERSION
        ? new FullExporterFactory()
        : new TrialExporterFactory();
    new Web(arguments, exporterFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, exporterFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
源代码25 项目: james-project   文件: MailAddressTest.java
@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);
}
 
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;
}
 
源代码27 项目: ShoppingCartinJava   文件: ForgotPassword.java
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();
}
 
源代码28 项目: occurrence   文件: DownloadEmailUtils.java
/**
 * 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;
}
 
源代码29 项目: camunda-bpm-mail   文件: MailTestUtil.java
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;
}
 
源代码30 项目: lemon   文件: SMTPAppenderBase.java
InternetAddress getAddress(String addressStr) {
    try {
        return new InternetAddress(addressStr);
    } catch (AddressException e) {
        addError("Could not parse address [" + addressStr + "].", e);

        return null;
    }
}
 
 类所在包
 同包方法