Example usage for javax.mail BodyPart setFileName

List of usage examples for javax.mail BodyPart setFileName

Introduction

In this page you can find the example usage for javax.mail BodyPart setFileName.

Prototype

public void setFileName(String filename) throws MessagingException;

Source Link

Document

Set the filename associated with this part, if possible.

Usage

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data/* w  ww.j av a  2  s .com*/
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Send a Multipart text message with attached files. FIXME: use
 * prepareMessage method/*from   w w  w . j  av a 2 s.  c o m*/
 *
 * @param strRecipientsTo
 *            The list of the main recipients email.Every recipient must be
 *            separated by the mail separator defined in config.properties
 * @param strRecipientsCc
 *            The recipients list of the carbon copies .
 * @param strRecipientsBcc
 *            The recipients list of the blind carbon copies .
 * @param strSenderName
 *            The sender name.
 * @param strSenderEmail
 *            The sender email address.
 * @param strSubject
 *            The message subject.
 * @param strMessage
 *            The message.
 * @param fileAttachements
 *            The list of attached files
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occured during sending
 * @throws MessagingException
 *             If a messaging error occured
 */
protected static void sendMultipartMessageText(String strRecipientsTo, String strRecipientsCc,
        String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject,
        String strMessage, List<FileAttachment> fileAttachements, Transport transport, Session session)
        throws MessagingException, AddressException, SendFailedException {
    Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName,
            strSenderEmail, strSubject, session);
    msg.setHeader(HEADER_NAME, HEADER_VALUE);

    // Creation of the root part containing all the elements of the message
    MimeMultipart multipart = new MimeMultipart();

    // Creation of the html part, the "core" of the message
    BodyPart msgBodyPart = new MimeBodyPart();
    // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE );
    msgBodyPart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_PLAIN)
                    + AppPropertiesService.getProperty(PROPERTY_CHARSET))));
    multipart.addBodyPart(msgBodyPart);

    // add File Attachement
    if (fileAttachements != null) {
        for (FileAttachment fileAttachement : fileAttachements) {
            String strFileName = fileAttachement.getFileName();
            byte[] bContentFile = fileAttachement.getData();
            String strContentType = fileAttachement.getType();
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType);
            msgBodyPart = new MimeBodyPart();
            msgBodyPart.setDataHandler(new DataHandler(dataSource));
            msgBodyPart.setFileName(strFileName);
            msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT);
            multipart.addBodyPart(msgBodyPart);
        }
    }

    msg.setContent(multipart);

    sendMessage(msg, transport);
}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//from   w  w w  .  ja  va2s .co  m
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

/**
 * <p>/*from www.ja v a  2s.c  om*/
 * Create an Amazon IAM account and send the details by email.
 * </p>
 * <p>
 * Created elements:
 * </p>
 * <ul>
 * <li>password to login to the management console if none exists,</li>
 * <li>accesskey if none is active,</li>
 * <li></li>
 * </ul>
 *
 * @param userName valid email used as userName of the created account.
 */
public void createUser(@Nonnull final String userName, GetGroupResult groupDescriptor, String keyPairName)
        throws Exception {
    Preconditions.checkNotNull(userName, "Given userName can NOT be null");
    logger.info("Process user {}", userName);

    List<String> userAccountChanges = Lists.newArrayList();

    Map<String, String> templatesParams = Maps.newHashMap();
    templatesParams.put("awsCredentialsHome", "~/.aws");
    templatesParams.put("awsCommandLinesHome", "/opt/amazon-aws");

    User user;
    try {
        user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser();
    } catch (NoSuchEntityException e) {
        logger.debug("User {} does not exist, create it", userName, e);
        user = iam.createUser(new CreateUserRequest(userName)).getUser();
        userAccountChanges.add("Create user");
    }

    List<BodyPart> attachments = Lists.newArrayList();

    // AWS WEB MANAGEMENT CONSOLE LOGIN & PASSWORD
    try {
        LoginProfile loginProfile = iam.getLoginProfile(new GetLoginProfileRequest(user.getUserName()))
                .getLoginProfile();
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", "#your password has already been generated and sent to you#");

        logger.info("Login profile already exists {}", loginProfile);
    } catch (NoSuchEntityException e) {
        // manually add a number to ensure amazon policy is respected
        String password = RandomStringUtils.randomAlphanumeric(10) + random.nextInt(10);
        LoginProfile loginProfile = iam
                .createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password))
                .getLoginProfile();
        userAccountChanges.add("Create user.login");
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", password);
    }

    // ADD USER TO GROUP
    Group group = groupDescriptor.getGroup();
    List<User> groupMembers = groupDescriptor.getUsers();

    boolean isUserInGroup = Iterables.any(groupMembers, new Predicate<User>() {
        public boolean apply(User groupMember) {
            return userName.equals(groupMember.getUserName());
        }

        ;
    });

    if (!isUserInGroup) {
        logger.debug("Add user {} to group {}", user, group);
        iam.addUserToGroup(new AddUserToGroupRequest(group.getGroupName(), user.getUserName()));
        groupMembers.add(user);
        userAccountChanges.add("Add user to group");
    }

    // ACCESS KEY
    boolean activeAccessKeyExists = false;
    ListAccessKeysResult listAccessKeysResult = iam
            .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName()));
    for (AccessKeyMetadata accessKeyMetadata : listAccessKeysResult.getAccessKeyMetadata()) {
        StatusType status = StatusType.fromValue(accessKeyMetadata.getStatus());
        if (StatusType.Active.equals(status)) {
            logger.info("Access key {} ({}) is already active, don't create another one.",
                    accessKeyMetadata.getAccessKeyId(), accessKeyMetadata.getCreateDate());
            activeAccessKeyExists = true;
            templatesParams.put("accessKeyId", accessKeyMetadata.getAccessKeyId());
            templatesParams.put("accessKeySecretId",
                    "#accessKey has already been generated and the secretId has been sent to you#");

            break;
        }
    }

    if (!activeAccessKeyExists) {
        AccessKey accessKey = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()))
                .getAccessKey();
        userAccountChanges.add("Create user.accessKey");
        logger.debug("Created access key {}", accessKey);
        templatesParams.put("accessKeyId", accessKey.getAccessKeyId());
        templatesParams.put("accessKeySecretId", accessKey.getSecretAccessKey());

        // email attachment: aws-credentials.txt
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            templatesParams.put("attachedCredentialsFileName", awsCredentialsBodyPart.getFileName());
            String awsCredentials = FreemarkerUtils.generate(templatesParams,
                    "/fr/xebia/cloud/amazon/aws/iam/aws-credentials.txt.ftl");
            awsCredentialsBodyPart.setContent(awsCredentials, "text/plain");
            attachments.add(awsCredentialsBodyPart);
        }

    }

    // SSH KEY PAIR
    if (keyPairName == null) { // If keyPairName is null, generate it from the username
        if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) {
            keyPairName = userName.substring(0, userName.indexOf("@xebia."));
        } else {
            keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_");
        }
    }

    try {
        List<KeyPairInfo> keyPairInfos = ec2
                .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)).getKeyPairs();
        KeyPairInfo keyPairInfo = Iterables.getOnlyElement(keyPairInfos);
        logger.info("SSH key {} already exists. Don't overwrite it.", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyName", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyFingerprint", keyPairInfo.getKeyFingerprint());

        String sshKeyFileName = keyPairName + ".pem";
        URL sshKeyFileURL = Thread.currentThread().getContextClassLoader().getResource(sshKeyFileName);
        if (sshKeyFileURL != null) {
            logger.info("SSH Key file {} found.", sshKeyFileName);

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyFileName);
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(Resources.toString(sshKeyFileURL, Charsets.ISO_8859_1),
                    "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            logger.info("SSH Key file {} NOT found.", sshKeyFileName);
        }

    } catch (AmazonServiceException e) {
        if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) {
            // ssh key does not exist, create it
            KeyPair keyPair = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName)).getKeyPair();
            userAccountChanges.add("Create ssh key");

            logger.info("Created ssh key {}", keyPair);
            templatesParams.put("sshKeyName", keyPair.getKeyName());
            templatesParams.put("sshKeyFingerprint", keyPair.getKeyFingerprint());

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(keyPair.getKeyName() + ".pem");
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(keyPair.getKeyMaterial(), "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            throw e;
        }
    }

    // X509 SELF SIGNED CERTIFICATE
    Collection<SigningCertificate> certificates = iam
            .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName))
            .getCertificates();
    // filter active certificates
    certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() {
        @Override
        public boolean apply(SigningCertificate signingCertificate) {
            return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus()));
        }
    });

    if (certificates.isEmpty()) {
        java.security.KeyPair x509KeyPair = keyPairGenerator.generateKeyPair();
        X509Certificate x509Certificate = generateSelfSignedX509Certificate(userName, x509KeyPair);
        String x509CertificatePem = Pems.pem(x509Certificate);

        UploadSigningCertificateResult uploadSigningCertificateResult = iam.uploadSigningCertificate( //
                new UploadSigningCertificateRequest(x509CertificatePem).withUserName(user.getUserName()));
        SigningCertificate signingCertificate = uploadSigningCertificateResult.getCertificate();
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
        userAccountChanges.add("Create x509 certificate");

        logger.info("Created x509 certificate {}", signingCertificate);

        // email attachment: x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509PrivateKeyFileName", x509PrivateKeyBodyPart.getFileName());
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/x-x509-ca-cert");
            attachments.add(x509PrivateKeyBodyPart);
        }
        // email attachment: x509 certifiate pem
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509CertificateFileName", x509CertificateBodyPart.getFileName());
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/x-x509-ca-cert");
            attachments.add(x509CertificateBodyPart);
        }

    } else {
        SigningCertificate signingCertificate = Iterables.getFirst(certificates, null);
        logger.info("X509 certificate {} already exists", signingCertificate.getCertificateId());
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
    }

    sendEmail(templatesParams, attachments, userName);
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }/*  w w w.j  a va  2s .  c o m*/
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;/*from w  w  w  .  ja  v a 2s.  c o  m*/
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }/*ww w .j a  v  a2s  . c  o  m*/
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*w  ww  . j  ava 2 s .c om*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java

/** sendEmail method sends email after receiving input parameters */
@Override//from  w w w  . j ava  2 s  . c o m
public void sendEmail(String fromEmail, String toEmail, String subject, String body,
        List<Pair<String, InputStream>> attachments) throws IOException {
    notNull(fromEmail, "fromEmail must be non-null");
    notNull(toEmail, "toEmail must be non-null");
    notNull(subject, "subject must be non-null");
    notNull(body, "body must be non-null");
    notNull(attachments, "attachments must be non-null");

    if (StringUtils.isBlank(mailHost)) {
        throw new IOException("the mail server hostname has not been configured");
    }

    List<File> tempFiles = new LinkedList<>();

    try {
        InternetAddress emailAddr = new InternetAddress(toEmail);
        emailAddr.validate();

        Properties properties = createSessionProperties();

        Session session = Session.getDefaultInstance(properties);

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(fromEmail));
        mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr);
        mimeMessage.setSubject(subject);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        Holder<Long> bytesWritten = new Holder<>(0L);

        for (Pair<String, InputStream> attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            File file = File.createTempFile("email-sender-", ".dat");
            tempFiles.add(file);

            copyDataToTempFile(file, attachment.getValue(), bytesWritten);
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file)));
            messageBodyPart.setFileName(attachment.getKey());
            multipart.addBodyPart(messageBodyPart);
        }

        mimeMessage.setContent(multipart);

        send(mimeMessage);

        LOGGER.debug("Email sent to " + toEmail);

    } catch (AddressException e) {
        throw new IOException("invalid email address: email=" + toEmail, e);
    } catch (MessagingException e) {
        throw new IOException("message error occurred on send", e);
    } finally {
        tempFiles.forEach(file -> {
            if (!file.delete()) {
                LOGGER.debug("unable to delete tmp file: path={}", file);
            }
        });
    }
}

From source file:org.unitime.commons.Email.java

public void addAttachement(final FormFile file) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(new DataSource() {
        @Override/*from  w ww .ja  va  2 s .  c o m*/
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("No output stream.");
        }

        @Override
        public String getName() {
            return file.getFileName();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return file.getInputStream();
        }

        @Override
        public String getContentType() {
            return file.getContentType();
        }
    }));
    attachement.setFileName(file.getFileName());
    iBody.addBodyPart(attachement);
}