Search in sources :

Example 76 with AddressException

use of javax.mail.internet.AddressException in project dataverse by IQSS.

the class MailUtil method parseSystemAddress.

public static InternetAddress parseSystemAddress(String systemEmail) {
    if (systemEmail != null) {
        try {
            InternetAddress parsedSystemEmail = new InternetAddress(systemEmail);
            logger.fine("parsed system email: " + parsedSystemEmail);
            return parsedSystemEmail;
        } catch (AddressException ex) {
            logger.info("Email will not be sent due to invalid value in " + SystemEmail + " setting: " + ex);
            return null;
        }
    }
    logger.fine("Email will not be sent because the " + SystemEmail + " setting is null.");
    return null;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) AddressException(javax.mail.internet.AddressException)

Example 77 with AddressException

use of javax.mail.internet.AddressException in project ma-modules-public by infiniteautomation.

the class ReportWorkItem method execute.

@Override
public void execute() {
    try {
        ReportLicenseChecker.checkLicense();
    } catch (LicenseViolatedException e) {
        LOG.error("Your core license doesn't permit you to use the reports module.");
        reportInstance.setReportStartTime(Common.timer.currentTimeMillis());
        reportInstance.setReportEndTime(Common.timer.currentTimeMillis());
        reportInstance.setRecordCount(-1);
        reportDao.saveReportInstance(reportInstance);
        return;
    }
    LOG.debug("Running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
    reportInstance.setRunStartTime(System.currentTimeMillis());
    reportDao.saveReportInstance(reportInstance);
    Translations translations = Common.getTranslations();
    // Create a list of DataPointVOs to which the user has permission.
    DataPointDao dataPointDao = DataPointDao.instance;
    List<ReportDao.PointInfo> points = new ArrayList<ReportDao.PointInfo>(reportConfig.getPoints().size());
    for (ReportPointVO reportPoint : reportConfig.getPoints()) {
        DataPointVO point = dataPointDao.getDataPoint(reportPoint.getPointId());
        if (point != null && Permissions.hasDataPointReadPermission(user, point)) {
            String colour = null;
            try {
                if (!StringUtils.isBlank(reportPoint.getColour()))
                    colour = ColorUtils.toHexString(reportPoint.getColour()).substring(1);
            } catch (InvalidArgumentException e) {
            // Should never happen since the colour would have been validated on save, so just let it go
            // as null.
            }
            points.add(new ReportDao.PointInfo(point, colour, reportPoint.getWeight(), reportPoint.isConsolidatedChart(), reportPoint.getPlotType()));
        }
    }
    int recordCount = 0;
    try {
        if (!points.isEmpty()) {
            if (Common.databaseProxy.getNoSQLProxy() == null)
                recordCount = reportDao.runReportSQL(reportInstance, points);
            else
                recordCount = reportDao.runReportNoSQL(reportInstance, points);
        }
    } catch (RuntimeException e) {
        recordCount = -1;
        throw e;
    } catch (Throwable e) {
        recordCount = -1;
        throw new RuntimeException("Report instance failed", e);
    } finally {
        reportInstance.setRunEndTime(System.currentTimeMillis());
        reportInstance.setRecordCount(recordCount);
        reportDao.saveReportInstance(reportInstance);
    }
    if (reportConfig.isEmail()) {
        String inlinePrefix = "R" + System.currentTimeMillis() + "-" + reportInstance.getId() + "-";
        // TODO should we create different instances of the email based upon language and timezone?
        // We are creating an email from the result. Create the content.
        final ReportChartCreator creator = new ReportChartCreator(translations, TimeZone.getDefault());
        creator.createContent(host, port, reportInstance, reportDao, inlinePrefix, reportConfig.isIncludeData());
        // Create the to list
        Set<String> addresses = MailingListDao.instance.getRecipientAddresses(reportConfig.getRecipients(), new DateTime(reportInstance.getReportStartTime()));
        String[] toAddrs = addresses.toArray(new String[0]);
        // Create the email content object.
        EmailContent emailContent = new EmailContent(null, creator.getHtml(), Common.UTF8);
        // Add the consolidated chart
        if (creator.getImageData() != null)
            emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + ReportChartCreator.IMAGE_CONTENT_ID, creator.getImageData(), ImageChartUtils.getContentType()));
        // Add the point charts
        for (PointStatistics pointStatistics : creator.getPointStatistics()) {
            if (pointStatistics.getImageData() != null)
                emailContent.addInline(new EmailInline.ByteArrayInline(inlinePrefix + pointStatistics.getChartName(), pointStatistics.getImageData(), ImageChartUtils.getContentType()));
        }
        // Add optional images used by the template.
        for (String s : creator.getInlineImageList()) addImage(emailContent, s);
        // Check if we need to attach the data.
        if (reportConfig.isIncludeData()) {
            addFileAttachment(emailContent, reportInstance.getName() + ".csv", creator.getExportFile());
            addFileAttachment(emailContent, reportInstance.getName() + "Events.csv", creator.getEventFile());
            addFileAttachment(emailContent, reportInstance.getName() + "Comments.csv", creator.getCommentFile());
        }
        PostEmailRunnable[] postEmail = null;
        if (reportConfig.isIncludeData()) {
            // See that the temp file(s) gets deleted after the email is sent.
            PostEmailRunnable deleteTempFile = new PostEmailRunnable() {

                @Override
                public void run() {
                    for (File file : filesToDelete) {
                        if (!file.delete())
                            LOG.warn("Temp file " + file.getPath() + " not deleted");
                    }
                }
            };
            postEmail = new PostEmailRunnable[] { deleteTempFile };
        }
        try {
            TranslatableMessage lm = new TranslatableMessage("ftl.scheduledReport", reportConfig.getName());
            String subject = creator.getSubject();
            if (subject == null)
                subject = lm.translate(translations);
            EmailWorkItem.queueEmail(toAddrs, subject, emailContent, postEmail);
        } catch (AddressException e) {
            LOG.error(e);
        }
        if (reportConfig.isSchedule()) {
            // Delete the report instance.
            reportDao.deleteReportInstance(reportInstance.getId(), user.getId());
        }
    }
    LOG.debug("Finished running report with id " + reportConfig.getId() + ", instance id " + reportInstance.getId());
}
Also used : LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) ArrayList(java.util.ArrayList) EmailContent(com.serotonin.web.mail.EmailContent) DateTime(org.joda.time.DateTime) InvalidArgumentException(com.serotonin.InvalidArgumentException) AddressException(javax.mail.internet.AddressException) ReportPointVO(com.serotonin.m2m2.reports.vo.ReportPointVO) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) PointStatistics(com.serotonin.m2m2.reports.web.ReportChartCreator.PointStatistics) PostEmailRunnable(com.serotonin.m2m2.email.PostEmailRunnable) ReportDao(com.serotonin.m2m2.reports.ReportDao) Translations(com.serotonin.m2m2.i18n.Translations) File(java.io.File)

Example 78 with AddressException

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

the class RegistrationManager method sendNewUserNotificationMessage.

/**
 * Send a notification messaged to the given notification email address about the registratoin of
 * the given new identity.
 * @param notificationMailAddress Email address who should be notified. MUST NOT BE NULL
 * @param newIdentity The newly registered Identity
 */
public void sendNewUserNotificationMessage(String notificationMailAddress, Identity newIdentity) {
    Address from;
    Address[] to;
    try {
        // fxdiff: change from/replyto, see FXOLAT-74
        from = new InternetAddress(WebappHelper.getMailConfig("mailReplyTo"));
        to = new Address[] { new InternetAddress(notificationMailAddress) };
    } catch (AddressException e) {
        log.error("Could not send registration notification message, bad mail address", e);
        return;
    }
    MailerResult result = new MailerResult();
    User user = newIdentity.getUser();
    Locale loc = I18nModule.getDefaultLocale();
    String[] userParams = new String[] { newIdentity.getName(), user.getProperty(UserConstants.FIRSTNAME, loc), user.getProperty(UserConstants.LASTNAME, loc), UserManager.getInstance().getUserDisplayEmail(user, loc), user.getPreferences().getLanguage(), Settings.getServerDomainName() + WebappHelper.getServletContextPath() };
    Translator trans = Util.createPackageTranslator(RegistrationManager.class, loc);
    String subject = trans.translate("reg.notiEmail.subject", userParams);
    String body = trans.translate("reg.notiEmail.body", userParams);
    MimeMessage msg = mailManager.createMimeMessage(from, to, null, null, body, subject, null, result);
    mailManager.sendMessage(msg, result);
    if (result.getReturnCode() != MailerResult.OK) {
        log.error("Could not send registration notification message, MailerResult was ::" + result.getReturnCode(), null);
    }
}
Also used : Locale(java.util.Locale) InternetAddress(javax.mail.internet.InternetAddress) User(org.olat.core.id.User) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MailerResult(org.olat.core.util.mail.MailerResult) Translator(org.olat.core.gui.translator.Translator) MimeMessage(javax.mail.internet.MimeMessage) AddressException(javax.mail.internet.AddressException)

Example 79 with AddressException

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

the class MailManagerImpl method createMimeMessage.

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) {
    if (from == null || ((tos == null || tos.length == 0) && ((ccs == null || ccs.length == 0)) && (bccs == null || bccs.length == 0)))
        return null;
    try {
        MimeMessage msg = createMessage(subject, from);
        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }
        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }
        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }
        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }
            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        log.error("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 80 with AddressException

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

the class MailManagerImpl method createAddress.

private Address createAddress(Identity recipient, MailerResult result, boolean error) {
    if (recipient != null) {
        if (recipient.getStatus() == Identity.STATUS_LOGIN_DENIED) {
            result.addFailedIdentites(recipient);
        } else {
            String emailAddress = recipient.getUser().getProperty(UserConstants.EMAIL, null);
            if (!StringHelper.containsNonWhitespace(emailAddress))
                return null;
            Address address;
            try {
                address = createAddress(emailAddress);
                if (address == null) {
                    result.addFailedIdentites(recipient);
                    if (error) {
                        result.setReturnCode(MailerResult.RECIPIENT_ADDRESS_ERROR);
                    }
                }
                return address;
            } catch (AddressException e) {
                result.addFailedIdentites(recipient);
                if (error) {
                    result.setReturnCode(MailerResult.RECIPIENT_ADDRESS_ERROR);
                }
            }
        }
    }
    return null;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) AddressException(javax.mail.internet.AddressException)

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