Search in sources :

Example 66 with Multipart

use of javax.mail.Multipart in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Session(javax.mail.Session)

Example 67 with Multipart

use of javax.mail.Multipart in project google-app-engine-jappstart by taylorleese.

the class MailService method sendActivationEmail.

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();
    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));
    textPart.setContent(messageSource.getMessage("mail.body.txt", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");
    htmlPart.setContent(messageSource.getMessage("mail.body.html", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");
    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);
    Transport.send(message);
}
Also used : Locale(java.util.Locale) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Properties(java.util.Properties) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 68 with Multipart

use of javax.mail.Multipart in project openolat by klemens.

the class MailManagerImpl method createForwardMimeMessage.

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) {
    try {
        MimeMessage msg = createMessage(subject, from);
        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }
        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 (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                BodyPart messageBodyPart = new MimeBodyPart();
                VFSLeaf data = getAttachmentDatas(attachment);
                DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            // 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 (MessagingException | UnsupportedEncodingException e) {
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) 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) DBMailAttachment(org.olat.core.util.mail.model.DBMailAttachment) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 69 with Multipart

use of javax.mail.Multipart in project openolat by klemens.

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 70 with Multipart

use of javax.mail.Multipart in project ddf by codice.

the class SmtpClientImplITCaseTest method testSendWithAttachments.

@Test
public void testSendWithAttachments() throws IOException, MessagingException, ExecutionException, InterruptedException {
    int port = findAvailablePort();
    SimpleSmtpServer server = SimpleSmtpServer.start(port);
    SmtpClientImpl emailService = new SmtpClientImpl(null);
    emailService.setSecurityLogger(mock(SecurityLogger.class));
    emailService.setHostName(HOSTNAME);
    emailService.setPortNumber(port);
    File tmpFile = folder.newFile("email.txt");
    try (OutputStream os = new FileOutputStream(tmpFile)) {
        os.write(ATTACHMENT_TEXT.getBytes());
    }
    Session session = emailService.createSession();
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
    mimeMessage.setSubject(SUBJECT);
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(BODY);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(tmpFile)));
    messageBodyPart.setFileName(ATTACHMENT_FILENAME);
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);
    emailService.send(mimeMessage).get();
    server.stop();
    List<SmtpMessage> emails = server.getReceivedEmails();
    assertThat(emails, hasSize(1));
    SmtpMessage email = emails.get(0);
    assertNotNull("The email was null.", email);
    assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
    assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
    assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
    assertThat(email.getBody(), containsString(BODY));
    assertThat(email.getBody(), containsString(ATTACHMENT_TEXT));
    assertThat(email.getBody(), containsString(ATTACHMENT_FILENAME));
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) SmtpMessage(com.dumbster.smtp.SmtpMessage) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DataHandler(javax.activation.DataHandler) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileOutputStream(java.io.FileOutputStream) SimpleSmtpServer(com.dumbster.smtp.SimpleSmtpServer) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) SecurityLogger(ddf.security.audit.SecurityLogger) Session(javax.mail.Session) Test(org.junit.Test)

Aggregations

Multipart (javax.mail.Multipart)148 MimeMultipart (javax.mail.internet.MimeMultipart)107 MimeBodyPart (javax.mail.internet.MimeBodyPart)92 MimeMessage (javax.mail.internet.MimeMessage)82 BodyPart (javax.mail.BodyPart)62 InternetAddress (javax.mail.internet.InternetAddress)61 MessagingException (javax.mail.MessagingException)58 Session (javax.mail.Session)44 DataHandler (javax.activation.DataHandler)42 IOException (java.io.IOException)37 Properties (java.util.Properties)37 Date (java.util.Date)30 Message (javax.mail.Message)30 FileDataSource (javax.activation.FileDataSource)27 DataSource (javax.activation.DataSource)24 InputStream (java.io.InputStream)23 File (java.io.File)21 Part (javax.mail.Part)21 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11