Search in sources :

Example 91 with AddressException

use of javax.mail.internet.AddressException in project wso2-axis2-transports by wso2.

the class PollTableEntry method loadConfiguration.

@Override
public boolean loadConfiguration(ParameterInclude paramIncl) throws AxisFault {
    String address = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ADDRESS);
    if (address == null) {
        return false;
    } else {
        try {
            emailAddress = new InternetAddress(address);
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '" + MailConstants.TRANSPORT_MAIL_ADDRESS + "' parameter :: " + e.getMessage());
        }
        List<Parameter> params = paramIncl.getParameters();
        Properties props = new Properties();
        for (Parameter p : params) {
            if (p.getName().startsWith("mail.")) {
                props.setProperty(p.getName(), (String) p.getValue());
            }
            if (MailConstants.MAIL_POP3_USERNAME.equals(p.getName()) || MailConstants.MAIL_IMAP_USERNAME.equals(p.getName())) {
                userName = (String) p.getValue();
            }
            if (MailConstants.MAIL_POP3_PASSWORD.equals(p.getName()) || MailConstants.MAIL_IMAP_PASSWORD.equals(p.getName())) {
                password = (String) p.getValue();
            }
            if (MailConstants.TRANSPORT_MAIL_PROTOCOL.equals(p.getName())) {
                protocol = (String) p.getValue();
            }
        }
        session = Session.getInstance(props, null);
        MailUtils.setupLogging(session, log, paramIncl);
        contentType = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_CONTENT_TYPE);
        try {
            String replyAddress = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS);
            if (replyAddress != null) {
                this.replyAddress = new InternetAddress(replyAddress);
            }
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '" + MailConstants.TRANSPORT_MAIL_REPLY_ADDRESS + "' parameter :: " + e.getMessage());
        }
        folder = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_FOLDER);
        addPreserveHeaders(ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_PRESERVE_HEADERS));
        addRemoveHeaders(ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_REMOVE_HEADERS));
        String option = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ACTION_AFTER_PROCESS);
        actionAfterProcess = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE : PollTableEntry.DELETE;
        option = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_ACTION_AFTER_FAILURE);
        actionAfterFailure = MailTransportListener.MOVE.equals(option) ? PollTableEntry.MOVE : PollTableEntry.DELETE;
        moveAfterProcess = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_MOVE_AFTER_PROCESS);
        moveAfterFailure = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_MOVE_AFTER_FAILURE);
        String processInParallel = ParamUtils.getOptionalParam(paramIncl, MailConstants.TRANSPORT_MAIL_PROCESS_IN_PARALLEL);
        if (processInParallel != null) {
            processingMailInParallel = Boolean.parseBoolean(processInParallel);
            if (log.isDebugEnabled() && processingMailInParallel) {
                log.debug("Parallel mail processing enabled for : " + address);
            }
        }
        String pollInParallel = ParamUtils.getOptionalParam(paramIncl, BaseConstants.TRANSPORT_POLL_IN_PARALLEL);
        if (pollInParallel != null) {
            setConcurrentPollingAllowed(Boolean.parseBoolean(pollInParallel));
            if (log.isDebugEnabled() && isConcurrentPollingAllowed()) {
                log.debug("Concurrent mail polling enabled for : " + address);
            }
        }
        String strMaxRetryCount = ParamUtils.getOptionalParam(paramIncl, MailConstants.MAX_RETRY_COUNT);
        if (strMaxRetryCount != null) {
            maxRetryCount = Integer.parseInt(strMaxRetryCount);
        }
        String strReconnectTimeout = ParamUtils.getOptionalParam(paramIncl, MailConstants.RECONNECT_TIMEOUT);
        if (strReconnectTimeout != null) {
            reconnectTimeout = Integer.parseInt(strReconnectTimeout) * 1000;
        }
        return super.loadConfiguration(paramIncl);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) Parameter(org.apache.axis2.description.Parameter) Properties(java.util.Properties)

Example 92 with AddressException

use of javax.mail.internet.AddressException in project hub-alert by blackducksoftware.

the class EmailGlobalTestAction method testConfigModelContent.

public ConfigurationTestResult testConfigModelContent(String testAddress, EmailGlobalConfigModel emailGlobalConfigModel) {
    if (StringUtils.isBlank(testAddress)) {
        return ConfigurationTestResult.failure("Could not determine what email address to send this content to. testAddress was not provided or was blank. Please provide a valid email address to test the configuration.");
    }
    try {
        InternetAddress emailAddress = new InternetAddress(testAddress);
        emailAddress.validate();
    } catch (AddressException ex) {
        return ConfigurationTestResult.failure(String.format("%s is not a valid email address. %s", testAddress, ex.getMessage()));
    }
    EmailChannelMessageModel testMessage = EmailChannelMessageModel.simple(TEST_SUBJECT_LINE, TEST_MESSAGE_CONTENT, "", "");
    SmtpConfigBuilder smtpConfigBuilder = SmtpConfig.builder();
    smtpConfigBuilder.setJavamailProperties(javamailPropertiesFactory.createJavaMailProperties(emailGlobalConfigModel));
    emailGlobalConfigModel.getSmtpFrom().ifPresent(smtpConfigBuilder::setSmtpFrom);
    emailGlobalConfigModel.getSmtpHost().ifPresent(smtpConfigBuilder::setSmtpHost);
    emailGlobalConfigModel.getSmtpPort().ifPresent(smtpConfigBuilder::setSmtpPort);
    emailGlobalConfigModel.getSmtpAuth().ifPresent(smtpConfigBuilder::setSmtpAuth);
    emailGlobalConfigModel.getSmtpUsername().ifPresent(smtpConfigBuilder::setSmtpUsername);
    if (BooleanUtils.toBoolean(emailGlobalConfigModel.getIsSmtpPasswordSet()) && emailGlobalConfigModel.getSmtpPassword().isEmpty()) {
        // TODO: This assumes if the password is saved but not provided we only test using the default configuration password.
        // If the UI supports multiple configurations in the future we should determine which configuration to get the password from.
        configurationAccessor.getConfiguration().flatMap(EmailGlobalConfigModel::getSmtpPassword).ifPresent(emailGlobalConfigModel::setSmtpPassword);
    }
    emailGlobalConfigModel.getSmtpPassword().ifPresent(smtpConfigBuilder::setSmtpPassword);
    SmtpConfig smtpConfig = smtpConfigBuilder.build();
    try {
        EmailTarget emailTarget = emailChannelMessagingService.createTarget(testMessage, testAddress);
        MessageResult messageResult = emailChannelMessagingService.sendMessage(smtpConfig, emailTarget);
        return ConfigurationTestResult.success(messageResult.getStatusMessage());
    } catch (AlertException ex) {
        return ConfigurationTestResult.failure(ex.getMessage());
    }
}
Also used : SmtpConfigBuilder(com.synopsys.integration.alert.service.email.SmtpConfigBuilder) SmtpConfig(com.synopsys.integration.alert.service.email.SmtpConfig) InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) EmailChannelMessageModel(com.synopsys.integration.alert.channel.email.distribution.EmailChannelMessageModel) EmailTarget(com.synopsys.integration.alert.service.email.EmailTarget) MessageResult(com.synopsys.integration.alert.common.message.model.MessageResult) AlertException(com.synopsys.integration.alert.api.common.model.exception.AlertException)

Example 93 with AddressException

use of javax.mail.internet.AddressException in project hub-alert by blackducksoftware.

the class EmailGlobalFieldModelTestAction method testConfig.

@Override
public MessageResult testConfig(String configId, FieldModel fieldModel, FieldUtility registeredFieldValues) throws AlertException {
    String addressString = fieldModel.getFieldValue(FieldModelTestAction.KEY_DESTINATION_NAME).orElse("");
    if (StringUtils.isBlank(addressString)) {
        throw new AlertException(String.format("Could not determine what email address to send this content to. %s was not provided or was blank. Please provide a valid email address to test the configuration.", FieldModelTestAction.KEY_DESTINATION_NAME));
    }
    try {
        InternetAddress emailAddress = new InternetAddress(addressString);
        emailAddress.validate();
    } catch (AddressException ex) {
        throw new AlertException(String.format("%s is not a valid email address. %s", addressString, ex.getMessage()));
    }
    EmailChannelMessageModel testMessage = EmailChannelMessageModel.simple(TEST_SUBJECT_LINE, TEST_MESSAGE_CONTENT, "", "");
    EmailTarget emailTarget = emailChannelMessagingService.createTarget(testMessage, addressString);
    SmtpConfig smtpConfig = SmtpConfig.builder().setJavamailProperties(javamailPropertiesFactory.createJavaMailProperties(registeredFieldValues)).setSmtpFrom(registeredFieldValues.getString(EmailPropertyKeys.JAVAMAIL_FROM_KEY.getPropertyKey()).orElse(null)).setSmtpHost(registeredFieldValues.getString(EmailPropertyKeys.JAVAMAIL_HOST_KEY.getPropertyKey()).orElse(null)).setSmtpPort(registeredFieldValues.getInteger(EmailPropertyKeys.JAVAMAIL_PORT_KEY.getPropertyKey()).orElse(-1)).setSmtpAuth(registeredFieldValues.getBooleanOrFalse(EmailPropertyKeys.JAVAMAIL_AUTH_KEY.getPropertyKey())).setSmtpUsername(registeredFieldValues.getString(EmailPropertyKeys.JAVAMAIL_USER_KEY.name()).orElse(null)).setSmtpPassword(registeredFieldValues.getString(EmailPropertyKeys.JAVAMAIL_PASSWORD_KEY.getPropertyKey()).orElse(null)).build();
    return emailChannelMessagingService.sendMessage(smtpConfig, emailTarget);
}
Also used : SmtpConfig(com.synopsys.integration.alert.service.email.SmtpConfig) InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) EmailChannelMessageModel(com.synopsys.integration.alert.channel.email.distribution.EmailChannelMessageModel) EmailTarget(com.synopsys.integration.alert.service.email.EmailTarget) AlertException(com.synopsys.integration.alert.api.common.model.exception.AlertException)

Example 94 with AddressException

use of javax.mail.internet.AddressException in project LAMSADE-tools by LAntoine.

the class Util method sendEmail.

/**
 * Sends an email to an address passed by parameter. If there is an error
 * other than lack of an Internet connection, the program will exit with a
 * stack trace.
 *
 * @param to_address
 *            the address to send the email to
 * @param filename
 *            if it's not empty, it will send the file referenced to by the
 *            filename as an attachment
 * @throws IllegalStateException
 * @returns 0 if it all went well, -1 if there was some error.
 */
public static int sendEmail(String to_address, String filename) throws IllegalStateException {
    int smtp_port = 465;
    String smtp_host = "smtp.gmail.com";
    String smtp_username = "lamsade.tools@gmail.com";
    String smtp_password = "z}}VC_-7{3bk^?*q^qZ4Z>G<5cgN&un&@>wU`gyza]kR(2v/&j!*6*s?H[^w=52e";
    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtp_host);
    props.put("mail.smtps.auth", true);
    props.put("mail.smtps.starttls.enable", true);
    props.put("mail.smtps.debug", true);
    Session session = Session.getInstance(props, null);
    Message message = new MimeMessage(session);
    logger.info("Trying to send an email to " + to_address);
    try {
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to_address));
        } catch (AddressException e) {
            logger.error("There is a problem with the address");
            throw new IllegalStateException(e);
        }
        message.setFrom(new InternetAddress(smtp_username));
        message.setSubject("New Mission Order");
        message.setText("Email Test Body");
        Multipart multipart = new MimeMultipart();
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("Une conference a été partagée avec vous", "text/html");
        MimeBodyPart attachPart = new MimeBodyPart();
        String attachFile = filename;
        attachPart.attachFile(attachFile);
        // adds parts to the multipart
        multipart.addBodyPart(messageBodyPart);
        multipart.addBodyPart(attachPart);
        // sets the multipart as message's content
        message.setContent(multipart);
        Transport transport = session.getTransport("smtps");
        try {
            transport.connect(smtp_host, smtp_port, smtp_username, smtp_password);
        } catch (MessagingException e) {
            logger.debug("There seems to be a problem with the connection. Try again later");
            return -1;
        }
        try {
            transport.sendMessage(message, message.getAllRecipients());
        } catch (SendFailedException e) {
            logger.error("Something went wrong trying to send the message");
            throw new IllegalStateException(e);
        }
        transport.close();
    } catch (MessagingException e) {
        logger.error("Something went wrong with building the message");
        throw new IllegalStateException(e);
    } catch (IOException e) {
        logger.error("Error in trying to add the attachment");
        throw new IllegalStateException(e);
    }
    logger.info("Email sent successfully");
    return 0;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) MimeBodyPart(javax.mail.internet.MimeBodyPart) Transport(javax.mail.Transport) Session(javax.mail.Session)

Example 95 with AddressException

use of javax.mail.internet.AddressException in project iaf by ibissource.

the class IbisExceptionTest method exceptionWithSpecificDetails.

@Test
public void exceptionWithSpecificDetails() {
    SenderException exception = new SenderException(new AddressException("test", "ref", 14));
    String result = exception.getMessage();
    assertEquals("(AddressException) [ref] at column [15]: test", result);
}
Also used : AddressException(javax.mail.internet.AddressException) Test(org.junit.Test)

Aggregations

AddressException (javax.mail.internet.AddressException)130 InternetAddress (javax.mail.internet.InternetAddress)108 MimeMessage (javax.mail.internet.MimeMessage)43 MessagingException (javax.mail.MessagingException)38 ArrayList (java.util.ArrayList)23 IOException (java.io.IOException)21 UnsupportedEncodingException (java.io.UnsupportedEncodingException)21 Address (javax.mail.Address)21 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)18 Properties (java.util.Properties)18 Session (javax.mail.Session)15 Date (java.util.Date)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)14 MimeMultipart (javax.mail.internet.MimeMultipart)12 File (java.io.File)11 Message (javax.mail.Message)10 Multipart (javax.mail.Multipart)9 DataHandler (javax.activation.DataHandler)8 Test (org.junit.Test)7 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)5