Search in sources :

Example 61 with Multipart

use of javax.mail.Multipart in project perun by CESNET.

the class MessagePreparator method prepare.

/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.mail.javamail.MimeMessagePreparator#prepare(javax.mail.internet.MimeMessage)
	 */
public void prepare(MimeMessage mimeMessage) throws Exception {
    MimeMultipart mpRoot = new MimeMultipart("mixed");
    Multipart mp = new MimeMultipart("alternative");
    // Create a body part to house the multipart/alternative Part
    MimeBodyPart contentPartRoot = new MimeBodyPart();
    contentPartRoot.setContent(mp);
    // Add the root body part to the root multipart
    mpRoot.addBodyPart(contentPartRoot);
    // adding recipients, cc and bcc
    if (getTo() != null) {
        for (String to : getTo()) {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
    }
    if (getCc() != null) {
        for (String cc : getCc()) {
            mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
        }
    }
    if (getBcc() != null) {
        for (String bcc : getBcc()) {
            mimeMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
        }
    }
    // adding from and subject
    mimeMessage.setFrom(new InternetAddress(getFrom()));
    mimeMessage.setSubject(getSubject());
    if (getEmailType().equals(EmailType.HTML)) {
        mp.addBodyPart(createHtmlMessage());
    } else if (getEmailType().equals(EmailType.PLAIN)) {
        mp.addBodyPart(createTextMessage());
    }
    // Create an "ATTACHMENT" - we must put it to mpRoot(mixed content)
    if (getFileNames() != null) {
        for (String filename : getFileNames()) {
            mpRoot.addBodyPart(createAttachment(filename));
        }
    }
    mimeMessage.setContent(mpRoot);
    logger.debug("Message is prepared to send");
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 62 with Multipart

use of javax.mail.Multipart in project KJFrameForAndroid by kymjs.

the class SimpleMailSender method sendHtmlMail.

/**
 * 以HTML格式发送邮件
 *
 * @param mailInfo
 *            待发送的邮件信息
 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    // 如果需要身份认证,则创建一个密码验证器
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 63 with Multipart

use of javax.mail.Multipart in project stanbol by apache.

the class SimpleMailExtractor method processContent.

// the recursive part
protected void processContent(Object content, StringBuilder buffer, RDFContainer rdf) throws MessagingException, IOException, ExtractorException {
    if (content instanceof String) {
        buffer.append(content);
        buffer.append(' ');
    } else if (content instanceof BodyPart) {
        BodyPart bodyPart = (BodyPart) content;
        DataHandler handler = bodyPart.getDataHandler();
        String encoding = null;
        if (handler != null) {
            encoding = MimeUtility.getEncoding(handler);
        }
        String fileName = bodyPart.getFileName();
        String contentType = bodyPart.getContentType();
        if (fileName != null) {
            try {
                fileName = MimeUtility.decodeWord(fileName);
            } catch (MessagingException e) {
            // happens on unencoded file names! so just ignore it and leave the file name as it is
            }
            URI attachURI = URIGenerator.createNewRandomUniqueURI();
            rdf.add(NMO.hasAttachment, attachURI);
            Model m = rdf.getModel();
            m.addStatement(attachURI, RDF.type, NFO.Attachment);
            m.addStatement(attachURI, NFO.fileName, fileName);
            if (handler != null) {
                if (encoding != null) {
                    m.addStatement(attachURI, NFO.encoding, encoding);
                }
            }
            if (contentType != null) {
                contentType = (new ContentType(contentType)).getBaseType();
                m.addStatement(attachURI, NIE.mimeType, contentType.trim());
            }
        // TODO: encoding?
        }
        // append the content, if any
        content = bodyPart.getContent();
        // remove any html markup if necessary
        if (contentType != null && content instanceof String) {
            contentType = contentType.toLowerCase();
            if (contentType.indexOf("text/html") >= 0) {
                if (encoding != null) {
                    encoding = MimeUtility.javaCharset(encoding);
                }
                content = extractTextFromHtml((String) content, encoding, rdf);
            }
        }
        processContent(content, buffer, rdf);
    } else if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        String subType = null;
        String contentType = multipart.getContentType();
        if (contentType != null) {
            ContentType ct = new ContentType(contentType);
            subType = ct.getSubType();
            if (subType != null) {
                subType = subType.trim().toLowerCase();
            }
        }
        if ("alternative".equals(subType)) {
            handleAlternativePart(multipart, buffer, rdf);
        } else if ("signed".equals(subType)) {
            handleProtectedPart(multipart, 0, buffer, rdf);
        } else if ("encrypted".equals(subType)) {
            handleProtectedPart(multipart, 1, buffer, rdf);
        } else {
            // handles multipart/mixed, /digest, /related, /parallel, /report and unknown subtypes
            handleMixedPart(multipart, buffer, rdf);
        }
    }
}
Also used : BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) Model(org.ontoware.rdf2go.model.Model) DataHandler(javax.activation.DataHandler) URI(org.ontoware.rdf2go.model.node.URI)

Example 64 with Multipart

use of javax.mail.Multipart in project jmeter by apache.

the class SendMailCommand method buildMessage.

/**
 * @return
 * @throws MessagingException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws AddressException
 */
private Message buildMessage() throws MessagingException, IOException {
    Message message;
    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) {
                // i.e. mailBody is empty
                File first = attachments.get(0);
                try (FileInputStream fis = new FileInputStream(first);
                    InputStream is = new BufferedInputStream(fis)) {
                    message.setText(IOUtils.toString(is, Charset.defaultCharset()));
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }
    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }
    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }
    if (null != subject) {
        message.setSubject(subject);
    }
    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }
    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }
    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }
    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) headerFields.get(i).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }
    return message;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Argument(org.apache.jmeter.config.Argument) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DataHandler(javax.activation.DataHandler) FileInputStream(java.io.FileInputStream) MimeMessage(javax.mail.internet.MimeMessage) BufferedInputStream(java.io.BufferedInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 65 with Multipart

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

the class SendAttachmentInEmail method main.

public static void main(String[] args) {
    // Recipient's email ID needs to be mentioned.
    String to = "destinationemail@gmail.com";
    // Sender's email ID needs to be mentioned
    String from = "fromemail@gmail.com";
    // change accordingly
    final String username = "manishaspatil";
    // change accordingly
    final String password = "******";
    // Assuming you are sending email through relay.jangosmtp.net
    String host = "relay.jangosmtp.net";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "25");
    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // Set Subject: header field
        message.setSubject("Testing Subject");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("This is message body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "/home/manisha/file.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

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