javax.mail.internet.MimeUtility Java Examples

The following examples show how to use javax.mail.internet.MimeUtility. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: cfMailMessageData.java    From openbd-core with GNU General Public License v3.0 7 votes vote down vote up
public static String getFilename( Part Mess ) throws MessagingException{
// Part.getFileName() doesn't take into account any encoding that may have been 
// applied to the filename so in order to obtain the correct filename we
// need to retrieve it from the Content-Disposition

String [] contentType = Mess.getHeader( "Content-Disposition" );
	if ( contentType != null && contentType.length > 0 ){
		int nameStartIndx = contentType[0].indexOf( "filename=\"" );
		if ( nameStartIndx != -1 ){
			String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) );
			try {
			filename = MimeUtility.decodeText( filename );
			return filename;
		} catch (UnsupportedEncodingException e) {}
		}  		
	}

	// couldn't determine it using the above, so fall back to more reliable but 
// less correct option
	return Mess.getFileName();
}
 
Example #2
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
String getReceivedFromHost() throws MessagingException {
    ensureMessage(false);

    String[] received = imessage.getHeader("Received");
    if (received == null || received.length == 0)
        return null;

    String origin = MimeUtility.unfold(received[received.length - 1]);

    String[] h = origin.split("\\s+");
    if (h.length > 1 && h[0].equalsIgnoreCase("from")) {
        String host = h[1];
        if (host.startsWith("["))
            host = host.substring(1);
        if (host.endsWith("]"))
            host = host.substring(0, host.length() - 1);
        if (!TextUtils.isEmpty(host))
            return host;
    }

    return null;
}
 
Example #3
Source File: DigestUtil.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate digest of given file with given algorithm. Writes digest to
 * file named filename.algorithm .
 * 
 * @param filename
 *            the String name of the file to be hashed
 * @param algorithm
 *            the algorithm to be used to compute the digest
 */
public static void digestFile(String filename, String algorithm) {
    byte[] b = new byte[65536];
    int read;
    try (FileInputStream fis = new FileInputStream(filename)) {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        while (fis.available() > 0) {
            read = fis.read(b);
            md.update(b, 0, read);
        }
        byte[] digest = md.digest();
        String fileNameBuffer = filename + "." + algorithm;
        try (FileOutputStream fos = new FileOutputStream(fileNameBuffer)) {
            OutputStream encodedStream = MimeUtility.encode(fos, "base64");
            encodedStream.write(digest);
            fos.flush();
        }
    } catch (Exception e) {
        LOGGER.error("Error computing Digest", e);
    }
}
 
Example #4
Source File: Pop3Util.java    From anyline with Apache License 2.0 6 votes vote down vote up
/**  
   * 获得邮件发件人  
   * @param msg 邮件内容  
   * @return 姓名 <Email地址>  
   */   
  public static String getFrom(MimeMessage msg){   
      String from = "";   
      Address[] froms; 
try { 
	froms = msg.getFrom(); 
       InternetAddress address = (InternetAddress) froms[0];   
       String person = address.getPersonal();   
       if (person != null) {   
           person = MimeUtility.decodeText(person) + " ";   
       } else {   
           person = "";   
       }   
       from = person + "<" + address.getAddress() + ">";   
} catch (Exception e) { 
	e.printStackTrace(); 
}   
      return from;   
  }
 
Example #5
Source File: EnvelopeBuilder.java    From james-project with Apache License 2.0 6 votes vote down vote up
private String headerValue(Headers message, String headerName) throws MailboxException {
    final Header header = MessageResultUtils.getMatching(headerName, message.headers());
    final String result;
    if (header == null) {
        result = null;
    } else {
        final String value = header.getValue();
        if (value == null || "".equals(value)) {
            result = null;
        } else {

            // ENVELOPE header values must be unfolded
            // See IMAP-269
            //
            //
            // IMAP-Servers are advised to also replace tabs with single spaces while doing the unfolding. This is what javamails
            // unfold does. mime4j's unfold does strictly follow the rfc and so preserve them
            //
            // See IMAP-327 and https://mailman2.u.washington.edu/mailman/htdig/imap-protocol/2010-July/001271.html
            result = MimeUtility.unfold(value);

        }
    }
    return result;
}
 
Example #6
Source File: DigestUtil.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate digest of given String using given algorithm. Encode digest in
 * MIME-like base64.
 * 
 * @param pass
 *            the String to be hashed
 * @param algorithm
 *            the algorithm to be used
 * @return String Base-64 encoding of digest
 * 
 * @throws NoSuchAlgorithmException
 *             if the algorithm passed in cannot be found
 */
public static String digestString(String pass, String algorithm) throws NoSuchAlgorithmException {

    MessageDigest md;
    ByteArrayOutputStream bos;

    try {
        md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(pass.getBytes("iso-8859-1"));
        bos = new ByteArrayOutputStream();
        OutputStream encodedStream = MimeUtility.encode(bos, "base64");
        encodedStream.write(digest);
        return bos.toString("iso-8859-1");
    } catch (IOException | MessagingException e) {
        throw new RuntimeException("Fatal error", e);
    }
}
 
Example #7
Source File: MailUtils.java    From scada with MIT License 6 votes vote down vote up
/**
 * ����ʼ�������
 * @param msg �ʼ�����
 * @return ���� <Email��ַ>
 */ 
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { 
    String from = ""; 
    Address[] froms = msg.getFrom(); 
    if (froms.length < 1){
    	//return "ϵͳ�ָ�";
        throw new MessagingException("û�з�����!");
    }         
    InternetAddress address = (InternetAddress) froms[0]; 
    String person = address.getPersonal(); 
    if (person != null) { 
        person = MimeUtility.decodeText(person) + " "; 
    } else { 
        person = ""; 
    } 
    from = person + "<" + address.getAddress() + ">"; 
     
    return from; 
}
 
Example #8
Source File: Email.java    From commons-email with Apache License 2.0 6 votes vote down vote up
/**
 * Create a folded header value containing 76 character chunks.
 *
 * @param name the name of the header
 * @param value the value of the header
 * @return the folded header value
 * @throws IllegalArgumentException if either the name or value is null or empty
 */
private String createFoldedHeaderValue(final String name, final String value)
{
    if (EmailUtils.isEmpty(name))
    {
        throw new IllegalArgumentException("name can not be null or empty");
    }
    if (value == null || EmailUtils.isEmpty(value))
    {
        throw new IllegalArgumentException("value can not be null or empty");
    }

    try
    {
        return MimeUtility.fold(name.length() + 2, MimeUtility.encodeText(value, this.charset, null));
    }
    catch (final UnsupportedEncodingException e)
    {
        return value;
    }
}
 
Example #9
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
String getSubject() throws MessagingException {
    ensureMessage(false);

    String subject = imessage.getHeader("Subject", null);
    if (subject == null)
        return null;

    subject = fixEncoding("subject", subject);
    subject = subject.replaceAll("\\?=[\\r\\n\\t ]+=\\?", "\\?==\\?");
    subject = MimeUtility.unfold(subject);
    subject = decodeMime(subject);

    return subject
            .trim()
            .replace("\n", "")
            .replace("\r", "");
}
 
Example #10
Source File: SendReceiveWithInternationalAddressTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws MessagingException, UnsupportedEncodingException {

    Session session = GreenMailUtil.getSession(ServerSetupTest.SMTP, properties);
    MimeMessage mimeMessage = new MockInternationalizedMimeMessage(session);
    mimeMessage.setSubject("subject");
    mimeMessage.setSentDate(new Date());
    mimeMessage.setFrom("múchätįldé@tìldę.oœ");
    mimeMessage.setRecipients(Message.RecipientType.TO, "用户@例子.广告");
    mimeMessage.setRecipients(Message.RecipientType.CC, "θσερεχα@μπλε.ψομ");
    mimeMessage.setRecipients(Message.RecipientType.BCC, "राममो@हन.ईन्फो");

    // The body text needs to be encoded if it contains non us-ascii characters
    mimeMessage.setText(MimeUtility.encodeText("用户@例子"));

    GreenMailUtil.sendMimeMessage(mimeMessage);

    // Decoding the body text to verify equality
    String decodedText = MimeUtility.decodeText(GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]));
    assertEquals("用户@例子", decodedText);
}
 
Example #11
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected static String decodeSubject(String subject) {
if (subject.contains("=?utf-8?")) {
	System.err.println("D: subject:\t" + subject);
	String decodedSubject = "";
      	for (String str: subject.replace("=?utf-8?", " =?utf-8?").split("\\s+"))
  			try {
  				decodedSubject += MimeUtility.decodeText(str);
  			} catch (UnsupportedEncodingException e) {
  				// TODO Auto-generated catch block
  				e.printStackTrace();
  			}
  		System.err.println("D: decoded:\t" + decodedSubject);
      	return decodedSubject;
  	} else
  		return subject;
  }
 
Example #12
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected static String decodeSubject(String subject) {
		if (subject.contains("=?utf-8?")) {
//			System.err.println("D: subject:\t" + subject);
			String decodedSubject = "";
        	for (String str: subject.replace("=?utf-8?", " =?utf-8?").split("\\s+"))
    			try {
    				decodedSubject += MimeUtility.decodeText(str);
    			} catch (UnsupportedEncodingException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
//    		System.err.println("D: decoded:\t" + decodedSubject);
        	return decodedSubject;
    	} else
    		return subject;
    }
 
Example #13
Source File: MailSender.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 发送邮件
 */
public void sendSimpleMail(MailSenderParams params) {
	 MimeMessage message = null;
     try {
         message = javaMailSender.createMimeMessage();
         MimeMessageHelper helper = new MimeMessageHelper(message, true);
         helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
         helper.setTo(params.getMailTo());
         helper.setSubject(params.getTitle());
         helper.setText(params.getContent(), true);
         this.addAttachment(helper,params);
     } catch (Exception e) {
         throw new RuntimeException("发送邮件异常! from: " + name+ "! to: " + params.getMailTo());
     }
     javaMailSender.send(message);
}
 
Example #14
Source File: MailSender.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 */
public void sendAttachmentMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        throw new RuntimeException("发送邮件异常! from: " + name + "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example #15
Source File: SendReceiveWithInternationalAddressTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
private void setAddressHeader(String name, InternetAddress[] addresses)
        throws MessagingException {

    try {

        // Encoding the email addresses so they are correctly sent to the mail server.
        for (int i = 0; i < addresses.length; i++) {
            String addStr = MimeUtility.encodeText(addresses[i].getAddress());
            InternetAddress ia = new InternetAddress();
            ia.setAddress(addStr);
            addresses[i] = ia;
        }

        String s = InternetAddress.toString(addresses, name.length() + 2);
        setHeader(name, s);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: GetMailMessageServiceTest.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
/**
 * Test execute method throws UnsupportedEncodingException.
 *
 * @throws Exception
 */
@Test
public void testExecuteUnsupportedEncodingException() throws Exception {
    doReturn(messageMock).when(serviceSpy).getMessage();
    doNothing().when(messageMock).setFlag(Flags.Flag.DELETED, true);
    doReturn(new String[]{"1"}).when(messageMock).getHeader(anyString());
    doReturn(SUBJECT_TEST).when(serviceSpy).changeHeaderCharset("1", CHARACTERSET);
    PowerMockito.mockStatic(MimeUtility.class);
    PowerMockito.doThrow(new UnsupportedEncodingException(StringUtils.EMPTY)).when(MimeUtility.class, "decodeText", anyString());

    addRequiredInputs();
    inputBuilder.subjectOnly(StringUtils.EMPTY);
    inputBuilder.characterSet(BAD_CHARACTERSET);

    exception.expect(Exception.class);
    exception.expectMessage("The given encoding (" + BAD_CHARACTERSET + ") is invalid or not supported.");
    serviceSpy.execute(inputBuilder.build());
}
 
Example #17
Source File: MailServiceImpl.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
private void sendMessage(MailDetail detail, String from) {
    log.info("Start to send html email for [{}({})]", detail.getToUsername(), detail.getToMailAddress());
    if (StringUtils.isEmpty(detail.getToMailAddress())) {
        log.warn("邮件接收者为空!");
        return;
    }
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("网站管理员") + "<" + from + ">");
        helper.setFrom(fromAddress);
        InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText(detail.getToMailAddress()) + "<" + detail.getToMailAddress() + ">");
        helper.setTo(toAddress);
        helper.setSubject(detail.getSubject());
        helper.setText(detail.getContent(), detail.isHtml());
        if (detail.getCc() != null && detail.getCc().length > 0) {
            helper.setCc(detail.getCc());
        }
        javaMailSender.send(message);
    } catch (MessagingException | UnsupportedEncodingException e) {
        log.error("Failed to send E-mail. e [{}]", e.getMessage());
    }
}
 
Example #18
Source File: FormHttpMessageConverter.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #19
Source File: POP3Client.java    From OA with GNU General Public License v3.0 5 votes vote down vote up
public static String getChineseFrom(String res) {
	String from = res;
	try {
		if (from.startsWith("=?GB") || from.startsWith("=?gb")
				|| from.startsWith("=?UTF")) {
			from = MimeUtility.decodeText(from);
		} else {
			from = new String(from.getBytes("ISO8859_1"), "GBK");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return from;
}
 
Example #20
Source File: cfPOP3.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private static String formatAddress( Address[] addList ){
	if ( addList == null || addList.length == 0 )
		return "";
	
	try {
		return MimeUtility.decodeText( javax.mail.internet.InternetAddress.toString( addList ) ).trim();
	} catch (UnsupportedEncodingException e) {
		return javax.mail.internet.InternetAddress.toString( addList );
	}
}
 
Example #21
Source File: MessageParser.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取消息附件中的文件.
 * @return List&lt;ResourceFileBean&gt;
 * 				文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public List<ResourceFileBean> getFiles() throws MessagingException, IOException {
	List<ResourceFileBean> resourceList = new ArrayList<ResourceFileBean>();
	Object content = message.getContent();
	Multipart mp = null;
	if (content instanceof Multipart) {
		mp = (Multipart) content;
	} else {
		return resourceList;
	}
	for (int i = 0, n = mp.getCount(); i < n; i++) {
		Part part = mp.getBodyPart(i);
		//此方法返回 Part 对象的部署类型。
		String disposition = part.getDisposition();
		//Part.ATTACHMENT 指示 Part 对象表示附件。
		//Part.INLINE 指示 Part 对象以内联方式显示。
		if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
			//part.getFileName():返回 Part 对象的文件名。
			String fileName = MimeUtility.decodeText(part.getFileName());
			//此方法为 Part 对象返回一个 InputStream 对象
			InputStream is = part.getInputStream();
			resourceList.add(new ResourceFileBean(fileName, is));
		} else if (disposition == null) {
			//附件也可以没有部署类型的方式存在
			getRelatedPart(part, resourceList);
		}
	}
	return resourceList;
}
 
Example #22
Source File: MailSender.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置要发送的附件,并对附件重命名
 * @param attachment
 * 				附件的集合,key 为附件的名称,value为附件
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws EmailException ;
 */
public void setMixMailRename(Map<String, File> attachment) throws MessagingException, UnsupportedEncodingException,
		EmailException {
	if (attachment != null) {
		for (String fileName : attachment.keySet()) {
			EmailAttachment attach = new EmailAttachment();
			attach.setPath(attachment.get(fileName).getAbsolutePath());
			attach.setName(MimeUtility.encodeText(fileName));
			email.attach(attach);
		}
	}
}
 
Example #23
Source File: MailSender.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置要发送的附件
 * @param attachment
 * 				附件数组
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws EmailException ;
 */
public void setMixMail(File[] attachment) throws MessagingException, UnsupportedEncodingException, EmailException {
	if (attachment != null) {
		for (File file : attachment) {
			EmailAttachment attach = new EmailAttachment();
			attach.setPath(file.getAbsolutePath());
			attach.setName(MimeUtility.encodeText(file.getName()));
			email.attach(attach);
		}
	}
}
 
Example #24
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #25
Source File: GetMailAttachmentService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private String downloadAttachment(Message message, String attachment, String characterSet, String path, boolean overwrite) throws Exception {
    if (!message.isMimeType(MimeTypes.TEXT_PLAIN) && !message.isMimeType(MimeTypes.TEXT_HTML)) {

        Multipart mpart = (Multipart) message.getContent();
        File f = new File(path);
        if (f.isDirectory()) {
            if (mpart != null) {
                for (int i = 0, n = mpart.getCount(); i < n; i++) {
                    Part part = mpart.getBodyPart(i);

                    if (input.isEncryptedMessage() && part.getContentType() != null &&
                            part.getContentType().equals(SecurityConstants.ENCRYPTED_CONTENT_TYPE)) {
                        part = decryptPart((MimeBodyPart) part);
                    }

                    if (part != null && part.getFileName() != null &&
                            (MimeUtility.decodeText(part.getFileName()).equalsIgnoreCase(attachment) ||
                                    part.getFileName().equalsIgnoreCase(attachment))
                    ) {
                        String disposition = part.getDisposition();
                        if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                            String partPrefix = part.getContentType().toLowerCase();
                            if (partPrefix.startsWith(io.cloudslang.content.mail.constants.MimeTypes.TEXT_PLAIN)) {
                                String attachmentContent = attachmentToString(part, characterSet);
                                writeTextToNewFile(path + "/" + attachment, attachmentContent, overwrite);
                                results.put(io.cloudslang.content.constants.OutputNames.RETURN_RESULT, MimeUtility.decodeText(attachmentContent));
                            } else {
                                writeNewFile(path + "/" + attachment, part, overwrite);
                            }
                        }
                        return MimeUtility.decodeText(part.getFileName());
                    }
                }
            }
        } else throw new Exception("The Folder " + path + " does not exist.");
    }
    throw new Exception("The email does not have an attached file by the name " + attachment + ".");
}
 
Example #26
Source File: MailManager.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
public static String getChineseFrom(String res) {
    String from = res;
    try {
        if (from.startsWith("=?GB") || from.startsWith("=?gb")
                || from.startsWith("=?UTF")) {
            from = MimeUtility.decodeText(from);
        } else {
            from = new String(from.getBytes("ISO8859_1"), "GBK");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return from;
}
 
Example #27
Source File: SubethaEmailMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter.
 * 
 * @param defaultPrefix This prefix fill be used for generating file name.
 * @param messagePart A part of message
 * @return File name.
 * @throws MessagingException
 */
private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException
{
    String fileName = messagePart.getFileName();
    if (fileName != null)
    {
        try
        {
            fileName = MimeUtility.decodeText(fileName);
        }
        catch (UnsupportedEncodingException ex)
        {
            // Nothing to do :)
        }
    }
    else
    {
        fileName = defaultPrefix;
        if (messagePart.isMimeType(MIME_PLAIN_TEXT))
            fileName += ".txt";
        else if (messagePart.isMimeType(MIME_HTML_TEXT))
            fileName += ".html";
        else if (messagePart.isMimeType(MIME_XML_TEXT))
            fileName += ".xml";
        else if (messagePart.isMimeType(MIME_IMAGE))
            fileName += ".gif";
    }
    return fileName;
}
 
Example #28
Source File: StandardMultipartHttpServletRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public static String decode(String value) {
	try {
		return MimeUtility.decodeText(value);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example #29
Source File: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Common part for sending message process :
 * <ul>
 * <li>initializes a mail session with the SMTP server</li>
 * <li>activates debugging</li>
 * <li>instantiates and initializes a mime message</li>
 * <li>sets the sent date, the from field, the subject field</li>
 * <li>sets the recipients</li>
 * </ul>
 *
 *
 * @return the message object initialized with the common settings
 * @param mail
 *            The mail to send
 * @param session
 *            The SMTP session object
 * @throws AddressException
 *             If invalid address
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static Message prepareMessage( MailItem mail, Session session ) throws MessagingException
{
    // Instantiate and initialize a mime message
    Message msg = new MimeMessage( session );
    msg.setSentDate( new Date( ) );

    try
    {
        msg.setFrom( new InternetAddress( mail.getSenderEmail( ), mail.getSenderName( ), AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) );
        msg.setSubject( MimeUtility.encodeText( mail.getSubject( ), AppPropertiesService.getProperty( PROPERTY_CHARSET ), ENCODING ) );
    }
    catch( UnsupportedEncodingException e )
    {
        throw new AppException( e.toString( ) );
    }

    // Instantiation of the list of address
    if ( mail.getRecipientsTo( ) != null )
    {
        msg.setRecipients( Message.RecipientType.TO, getAllAdressOfRecipients( mail.getRecipientsTo( ) ) );
    }

    if ( mail.getRecipientsCc( ) != null )
    {
        msg.setRecipients( Message.RecipientType.CC, getAllAdressOfRecipients( mail.getRecipientsCc( ) ) );
    }

    if ( mail.getRecipientsBcc( ) != null )
    {
        msg.setRecipients( Message.RecipientType.BCC, getAllAdressOfRecipients( mail.getRecipientsBcc( ) ) );
    }

    return msg;
}
 
Example #30
Source File: MultiPartEmail.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Attach a file specified as a DataSource interface.
 *
 * @param ds A DataSource interface for the file.
 * @param name The name field for the attachment.
 * @param description A description for the attachment.
 * @param disposition Either mixed or inline.
 * @return A MultiPartEmail.
 * @throws EmailException see javax.mail.internet.MimeBodyPart
 *  for definitions
 * @since 1.0
 */
public MultiPartEmail attach(
    final DataSource ds,
    String name,
    final String description,
    final String disposition)
    throws EmailException
{
    if (EmailUtils.isEmpty(name))
    {
        name = ds.getName();
    }
    final BodyPart bodyPart = createBodyPart();
    try
    {
        bodyPart.setDisposition(disposition);
        bodyPart.setFileName(MimeUtility.encodeText(name));
        bodyPart.setDescription(description);
        bodyPart.setDataHandler(new DataHandler(ds));

        getContainer().addBodyPart(bodyPart);
    }
    catch (final UnsupportedEncodingException uee)
    {
        // in case the file name could not be encoded
        throw new EmailException(uee);
    }
    catch (final MessagingException me)
    {
        throw new EmailException(me);
    }
    setBoolHasAttachments(true);

    return this;
}