Search in sources :

Example 81 with AddressException

use of javax.mail.internet.AddressException in project OpenOLAT by OpenOLAT.

the class MailManagerImpl method createFromAddress.

private Address createFromAddress(Identity recipient, MailerResult result) {
    if (recipient != null) {
        String emailAddress = recipient.getUser().getProperty(UserConstants.EMAIL, null);
        if (emailAddress == null) {
            emailAddress = WebappHelper.getMailConfig("mailFrom");
        }
        String name = recipient.getUser().getProperty(UserConstants.FIRSTNAME, null) + " " + recipient.getUser().getProperty(UserConstants.LASTNAME, null);
        Address address;
        try {
            address = createAddressWithName(emailAddress, name);
            if (address == null) {
                result.addFailedIdentites(recipient);
                result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
            }
            return address;
        } catch (AddressException e) {
            result.addFailedIdentites(recipient);
            result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        } catch (UnsupportedEncodingException e) {
            result.addFailedIdentites(recipient);
            result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        }
    }
    return null;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) AddressException(javax.mail.internet.AddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 82 with AddressException

use of javax.mail.internet.AddressException in project OpenOLAT by OpenOLAT.

the class MailManagerImpl method saveDBMessage.

protected DBMail saveDBMessage(MailContext context, Identity fromId, String from, Identity toId, String to, Identity cc, List<ContactList> bccLists, String metaId, MailContent content, MailerResult result) {
    try {
        DBMailImpl mail = new DBMailImpl();
        if (result == null) {
            result = new MailerResult();
        }
        boolean makeRealMail = makeRealMail(toId, cc, bccLists);
        Address fromAddress = null;
        List<Address> toAddress = new ArrayList<Address>();
        List<Address> ccAddress = new ArrayList<Address>();
        List<Address> bccAddress = new ArrayList<Address>();
        if (fromId != null) {
            DBMailRecipient fromRecipient = new DBMailRecipient();
            fromRecipient.setRecipient(fromId);
            if (StringHelper.containsNonWhitespace(from)) {
                fromRecipient.setEmailAddress(from);
                fromAddress = createFromAddress(from, result);
            } else {
                fromAddress = createFromAddress(fromId, result);
            }
            fromRecipient.setVisible(Boolean.TRUE);
            fromRecipient.setMarked(Boolean.FALSE);
            fromRecipient.setDeleted(Boolean.FALSE);
            mail.setFrom(fromRecipient);
        } else {
            if (!StringHelper.containsNonWhitespace(from)) {
                from = WebappHelper.getMailConfig("mailFrom");
            }
            DBMailRecipient fromRecipient = new DBMailRecipient();
            fromRecipient.setEmailAddress(from);
            fromRecipient.setVisible(Boolean.TRUE);
            fromRecipient.setMarked(Boolean.FALSE);
            // marked as delted as nobody can read it
            fromRecipient.setDeleted(Boolean.TRUE);
            mail.setFrom(fromRecipient);
            fromAddress = createFromAddress(from, result);
        }
        if (result.getReturnCode() != MailerResult.OK) {
            return null;
        }
        mail.setMetaId(metaId);
        String subject = content.getSubject();
        if (subject != null && subject.length() > 500) {
            log.warn("Cut a too long subkect in name. Size: " + subject.length(), null);
            subject = subject.substring(0, 500);
        }
        mail.setSubject(subject);
        String body = content.getBody();
        if (body != null && body.length() > 16777210) {
            log.warn("Cut a too long body in mail. Size: " + body.length(), null);
            body = body.substring(0, 16000000);
        }
        mail.setBody(body);
        mail.setLastModified(new Date());
        if (context != null) {
            OLATResourceable ores = context.getOLATResourceable();
            if (ores != null) {
                String resName = ores.getResourceableTypeName();
                if (resName != null && resName.length() > 50) {
                    log.warn("Cut a too long resourceable type name in mail context: " + resName, null);
                    resName = resName.substring(0, 49);
                }
                mail.getContext().setResName(ores.getResourceableTypeName());
                mail.getContext().setResId(ores.getResourceableId());
            }
            String resSubPath = context.getResSubPath();
            if (resSubPath != null && resSubPath.length() > 2000) {
                log.warn("Cut a too long resSubPath in mail context: " + resSubPath, null);
                resSubPath = resSubPath.substring(0, 2000);
            }
            mail.getContext().setResSubPath(resSubPath);
            String businessPath = context.getBusinessPath();
            if (businessPath != null && businessPath.length() > 2000) {
                log.warn("Cut a too long resSubPath in mail context: " + businessPath, null);
                businessPath = businessPath.substring(0, 2000);
            }
            mail.getContext().setBusinessPath(businessPath);
        }
        // add to
        DBMailRecipient recipientTo = null;
        if (toId != null) {
            recipientTo = new DBMailRecipient();
            if (toId instanceof IdentityImpl) {
                recipientTo.setRecipient(toId);
            } else {
                to = toId.getUser().getProperty(UserConstants.EMAIL, null);
            }
            if (StringHelper.containsNonWhitespace(to)) {
                recipientTo.setEmailAddress(to);
            }
            recipientTo.setVisible(Boolean.TRUE);
            recipientTo.setDeleted(Boolean.FALSE);
            recipientTo.setMarked(Boolean.FALSE);
            recipientTo.setRead(Boolean.FALSE);
        } else if (StringHelper.containsNonWhitespace(to)) {
            recipientTo = new DBMailRecipient();
            recipientTo.setEmailAddress(to);
            recipientTo.setVisible(Boolean.TRUE);
            recipientTo.setDeleted(Boolean.TRUE);
            recipientTo.setMarked(Boolean.FALSE);
            recipientTo.setRead(Boolean.FALSE);
        }
        if (recipientTo != null) {
            mail.getRecipients().add(recipientTo);
            createAddress(toAddress, recipientTo, true, result, true);
        }
        if (makeRealMail && StringHelper.containsNonWhitespace(to)) {
            createAddress(toAddress, to);
        }
        if (cc != null) {
            DBMailRecipient recipient = new DBMailRecipient();
            if (cc instanceof IdentityImpl) {
                recipient.setRecipient(cc);
            } else {
                recipient.setEmailAddress(cc.getUser().getProperty(UserConstants.EMAIL, null));
            }
            recipient.setVisible(Boolean.TRUE);
            recipient.setDeleted(Boolean.FALSE);
            recipient.setMarked(Boolean.FALSE);
            recipient.setRead(Boolean.FALSE);
            mail.getRecipients().add(recipient);
            createAddress(ccAddress, recipient, false, result, true);
        }
        // add bcc recipients
        appendRecipients(mail, bccLists, toAddress, bccAddress, false, makeRealMail, result);
        dbInstance.getCurrentEntityManager().persist(mail);
        // save attachments
        List<File> attachments = content.getAttachments();
        if (attachments != null && !attachments.isEmpty()) {
            for (File attachment : attachments) {
                FileInputStream in = null;
                try {
                    DBMailAttachment data = new DBMailAttachment();
                    data.setSize(attachment.length());
                    data.setName(attachment.getName());
                    long checksum = FileUtils.checksum(attachment, new Adler32()).getValue();
                    data.setChecksum(new Long(checksum));
                    data.setMimetype(WebappHelper.getMimeType(attachment.getName()));
                    in = new FileInputStream(attachment);
                    String path = saveAttachmentToStorage(data.getName(), data.getMimetype(), checksum, attachment.length(), in);
                    data.setPath(path);
                    data.setMail(mail);
                    dbInstance.getCurrentEntityManager().persist(data);
                } catch (FileNotFoundException e) {
                    log.error("File attachment not found: " + attachment, e);
                } catch (IOException e) {
                    log.error("Error with file attachment: " + attachment, e);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
        }
        if (makeRealMail) {
            // check that we send an email to someone
            if (!toAddress.isEmpty() || !ccAddress.isEmpty() || !bccAddress.isEmpty()) {
                sendRealMessage(fromAddress, toAddress, ccAddress, bccAddress, subject, body, attachments, result);
                if (result != null && !result.isSuccessful()) {
                    handleErrors(result, fromId, toId, cc, bccLists);
                }
            }
        }
        // update subscription
        for (DBMailRecipient recipient : mail.getRecipients()) {
            if (recipient.getRecipient() != null) {
                subscribe(recipient.getRecipient());
            }
        }
        SubscriptionContext subContext = getSubscriptionContext();
        notificationsManager.markPublisherNews(subContext, null, false);
        return mail;
    } catch (AddressException e) {
        log.error("Cannot send e-mail: ", e);
        result.setReturnCode(MailerResult.RECIPIENT_ADDRESS_ERROR);
        return null;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) MailerResult(org.olat.core.util.mail.MailerResult) OLATResourceable(org.olat.core.id.OLATResourceable) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) DBMailImpl(org.olat.core.util.mail.model.DBMailImpl) IdentityImpl(org.olat.basesecurity.IdentityImpl) IOException(java.io.IOException) Date(java.util.Date) FileInputStream(java.io.FileInputStream) Adler32(java.util.zip.Adler32) DBMailRecipient(org.olat.core.util.mail.model.DBMailRecipient) DBMailAttachment(org.olat.core.util.mail.model.DBMailAttachment) AddressException(javax.mail.internet.AddressException) SubscriptionContext(org.olat.core.commons.services.notifications.SubscriptionContext) File(java.io.File)

Example 83 with AddressException

use of javax.mail.internet.AddressException in project simple-email by codylerum.

the class MailUtility method internetAddress.

public static InternetAddress internetAddress(String address, String name) throws InvalidAddressException {
    InternetAddress internetAddress;
    try {
        internetAddress = new InternetAddress(address);
        internetAddress.setPersonal(name);
        return internetAddress;
    } catch (AddressException e) {
        throw new InvalidAddressException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InvalidAddressException(e);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) InvalidAddressException(com.outjected.email.api.InvalidAddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidAddressException(com.outjected.email.api.InvalidAddressException)

Example 84 with AddressException

use of javax.mail.internet.AddressException in project ANNIS by korpling.

the class CorpusAdministration method sendImportStatusMail.

public void sendImportStatusMail(String adress, String corpusPath, ImportJob.Status status, String additionalInfo) {
    if (adress == null || corpusPath == null) {
        return;
    }
    // check valid properties
    if (statusMailSender == null || statusMailSender.isEmpty()) {
        log.warn("Could not send status mail because \"annis.mail-sender\" " + "property was not configured in conf/annis-service-properties.");
        return;
    }
    try {
        SimpleEmail mail = new SimpleEmail();
        List<InternetAddress> to = new LinkedList<>();
        to.add(new InternetAddress(adress));
        StringBuilder sbMsg = new StringBuilder();
        sbMsg.append("Dear Sir or Madam,\n");
        sbMsg.append("\n");
        sbMsg.append("this is the requested status update to the ANNIS corpus import " + "you have started. Please note that this message is automated and " + "if you have any question regarding the import you have to ask the " + "administrator of the ANNIS instance directly.\n\n");
        mail.setTo(to);
        if (status == ImportJob.Status.SUCCESS) {
            mail.setSubject("ANNIS import finished successfully (" + corpusPath + ")");
            sbMsg.append("Status:\nThe corpus \"").append(corpusPath).append("\" was successfully imported and can be used from now on.\n");
        } else if (status == ImportJob.Status.ERROR) {
            mail.setSubject("ANNIS import *failed* (" + corpusPath + ")");
            sbMsg.append("Status:\nUnfortunally the corpus \"").append(corpusPath).append("\" could not be imported successfully. " + "You may ask the administrator of the ANNIS installation for " + "assistance why the corpus import failed.\n");
        } else if (status == ImportJob.Status.RUNNING) {
            mail.setSubject("ANNIS import started (" + corpusPath + ")");
            sbMsg.append("Status:\nThe import of the corpus \"").append(corpusPath).append("\" was started.\n");
        } else if (status == ImportJob.Status.WAITING) {
            mail.setSubject("ANNIS import was scheduled (" + corpusPath + ")");
            sbMsg.append("Status:\nThe import of the corpus \"").append(corpusPath).append("\" was scheduled and is currently waiting for other imports to " + "finish. As soon as the previous imports are finished this import " + "job will be executed.\n");
        } else {
            // we don't know how to handle this, just don't send a message
            return;
        }
        if (additionalInfo != null && !additionalInfo.isEmpty()) {
            sbMsg.append("Addtional information:\n");
            sbMsg.append(additionalInfo).append("\n");
        }
        sbMsg.append("\n\nSincerely yours,\n\nthe ANNIS import service.");
        mail.setMsg(sbMsg.toString());
        mail.setHostName("localhost");
        mail.setFrom(statusMailSender);
        mail.send();
        log.info("Send status ({}) mail to {}.", new String[] { status.name(), adress });
    } catch (AddressException | EmailException ex) {
        log.warn("Could not send mail: " + ex.getMessage());
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException) EmailException(org.apache.commons.mail.EmailException) SimpleEmail(org.apache.commons.mail.SimpleEmail) LinkedList(java.util.LinkedList)

Example 85 with AddressException

use of javax.mail.internet.AddressException in project oozie by apache.

the class SLAEmailEventListener method init.

@Override
public void init(Configuration conf) throws Exception {
    oozieBaseUrl = ConfigurationService.get(conf, OOZIE_BASE_URL);
    // Get SMTP properties from the configuration used in Email Action
    String smtpHost = conf.get(EmailActionExecutor.EMAIL_SMTP_HOST, SMTP_HOST_DEFAULT);
    String smtpPort = conf.get(EmailActionExecutor.EMAIL_SMTP_PORT, SMTP_PORT_DEFAULT);
    Boolean smtpAuth = conf.getBoolean(EmailActionExecutor.EMAIL_SMTP_AUTH, SMTP_AUTH_DEFAULT);
    String smtpUser = conf.get(EmailActionExecutor.EMAIL_SMTP_USER, "");
    String smtpPassword = ConfigurationService.getPassword(EmailActionExecutor.EMAIL_SMTP_PASS, "");
    String smtpConnectTimeout = conf.get(SMTP_CONNECTION_TIMEOUT, SMTP_CONNECTION_TIMEOUT_DEFAULT);
    String smtpTimeout = conf.get(SMTP_TIMEOUT, SMTP_TIMEOUT_DEFAULT);
    int blacklistTimeOut = Integer.valueOf(conf.get(BLACKLIST_CACHE_TIMEOUT, BLACKLIST_CACHE_TIMEOUT_DEFAULT));
    blacklistFailCount = Integer.valueOf(conf.get(BLACKLIST_FAIL_COUNT, BLACKLIST_FAIL_COUNT_DEFAULT));
    // blacklist email addresses causing SendFailedException with cache timeout
    blackList = CacheBuilder.newBuilder().expireAfterWrite(blacklistTimeOut, TimeUnit.SECONDS).build(new CacheLoader<String, AtomicInteger>() {

        @Override
        public AtomicInteger load(String key) throws Exception {
            return new AtomicInteger();
        }
    });
    // Set SMTP properties
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", smtpHost);
    properties.setProperty("mail.smtp.port", smtpPort);
    properties.setProperty("mail.smtp.auth", smtpAuth.toString());
    properties.setProperty("mail.smtp.connectiontimeout", smtpConnectTimeout);
    properties.setProperty("mail.smtp.timeout", smtpTimeout);
    try {
        fromAddr = new InternetAddress(conf.get("oozie.email.from.address", SMTP_SOURCE_DEFAULT));
    } catch (AddressException ae) {
        LOG.error("Bad Source Address specified in oozie.email.from.address", ae);
        throw ae;
    }
    if (!smtpAuth) {
        session = Session.getInstance(properties);
    } else {
        session = Session.getInstance(properties, new JavaMailAuthenticator(smtpUser, smtpPassword));
    }
    alertEvents = new HashSet<SLAEvent.EventStatus>();
    String alertEventsStr = ConfigurationService.get(conf, SLAService.CONF_ALERT_EVENTS);
    if (alertEventsStr != null) {
        String[] alertEvt = alertEventsStr.split(",", -1);
        for (String evt : alertEvt) {
            alertEvents.add(SLAEvent.EventStatus.valueOf(evt));
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AddressException(javax.mail.internet.AddressException) JavaMailAuthenticator(org.apache.oozie.action.email.EmailActionExecutor.JavaMailAuthenticator) CacheLoader(com.google.common.cache.CacheLoader) Properties(java.util.Properties)

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