Java 类javax.mail.internet.MimeUtility 实例源码
项目:jsf-core
文件:ReciveMail.java
/**
* 【保存附件】
*/
public void saveAttachMent(Part part) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
}
项目:lemon
文件:JavamailService.java
public static String getFrom(MimeMessage msg) throws MessagingException,
UnsupportedEncodingException {
String from = "";
Address[] froms = msg.getFrom();
if (froms.length < 1) {
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;
}
项目:ephesoft
文件:MailReceiverServiceImpl.java
private void downloadAttachment(Part part, String folderPath) throws MessagingException, IOException {
String disPosition = part.getDisposition();
String fileName = part.getFileName();
String decodedAttachmentName = null;
if (fileName != null) {
LOGGER.info("Attached File Name :: " + fileName);
decodedAttachmentName = MimeUtility.decodeText(fileName);
LOGGER.info("Decoded string :: " + decodedAttachmentName);
decodedAttachmentName = Normalizer.normalize(decodedAttachmentName, Normalizer.Form.NFC);
LOGGER.info("Normalized string :: " + decodedAttachmentName);
int extensionIndex = decodedAttachmentName.indexOf(EXTENSION_VALUE_46);
extensionIndex = extensionIndex == -1 ? decodedAttachmentName.length() : extensionIndex;
File parentFile = new File(folderPath);
LOGGER.info("Updating file name if any file with the same name exists. File : " + decodedAttachmentName);
decodedAttachmentName = FileUtils.getUpdatedFileNameForDuplicateFile(decodedAttachmentName.substring(0, extensionIndex), parentFile, -1)
+ decodedAttachmentName.substring(extensionIndex);
LOGGER.info("Updated file name : " + decodedAttachmentName);
}
if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
File file = new File(folderPath + File.separator + decodedAttachmentName);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
}
}
项目:txazo
文件:MimeEmail.java
private void parsePart(Part part) throws Exception {
if (part.isMimeType("text/*")) {
content.append((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
Part p = null;
Multipart multipart = (Multipart) part.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
p = multipart.getBodyPart(i);
String disposition = p.getDisposition();
if (disposition != null && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
attachments.add(MimeUtility.decodeText(p.getFileName()));
}
parsePart(p);
}
} else if (part.isMimeType("message/rfc822")) {
parsePart((Part) part.getContent());
}
}
项目:play
文件:MailHelper.java
/**
* �����Ĵ������ϴ�
*/
private void saveFile(Message message, BodyPart bp) throws Exception {
String fileName = bp.getFileName();
if ((fileName != null)) {
new File(dir).mkdirs(); // �½�Ŀ¼
fileName = MimeUtility.decodeText(fileName);
String suffix = fileName.substring(fileName.lastIndexOf("."));
String filePath = dir + "/" + UUID.randomUUID() + suffix;
message.attachMap.put(fileName, filePath);
File file = new File(filePath);
BufferedInputStream bis = new BufferedInputStream(bp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.close();
bis.close();
}
}
项目:openbd-core
文件:cfMailMessageData.java
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();
}
项目:James
文件:DigestUtil.java
/**
* 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 ioe) {
throw new RuntimeException("Fatal error: " + ioe);
} catch (MessagingException me) {
throw new RuntimeException("Fatal error: " + me);
}
}
项目:iBase4J-Common
文件:EmailSender.java
/**
* 设置发信人
*
* @param from
* @return
*/
public boolean setFrom(String from) {
if (from == null || from.trim().equals("")) {
from = PropertiesUtil.getString("email.send.from");
}
try {
String[] f = from.split(",");
if (f.length > 1) {
from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">";
}
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
return false;
}
}
项目:alfresco-repository
文件:SubethaEmailMessage.java
/**
* 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;
}
项目:alfresco-repository
文件:ContentModelMessage.java
/**
* This method builds {@link MimeMessage} based on {@link ContentModel}
*
* @throws MessagingException
*/
private void buildContentModelMessage() throws MessagingException
{
Map<QName, Serializable> properties = messageFileInfo.getProperties();
String prop = null;
setSentDate(messageFileInfo.getModifiedDate());
// Add FROM address
Address[] addressList = buildSenderFromAddress();
addFrom(addressList);
// Add TO address
addressList = buildRecipientToAddress();
addRecipients(RecipientType.TO, addressList);
prop = (String) properties.get(ContentModel.PROP_TITLE);
try
{
prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop;
prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null);
}
catch (UnsupportedEncodingException e)
{
// ignore
}
setSubject(prop);
setContent(buildContentModelMultipart());
}
项目:automat
文件:EmailSender.java
/**
* 设置发信人
*
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
if (from == null || from.trim().equals("")) {
from = PropertiesUtil.getString("email.send.from");
}
try {
String[] f = from.split(",");
if (f.length > 1) {
from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">";
}
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
return false;
}
}
项目:iBase4J
文件:EmailSender.java
/**
* 设置发信人
*
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
if (from == null || from.trim().equals("")) {
from = PropertiesUtil.getString("email.send.from");
}
try {
String[] f = from.split(",");
if (f.length > 1) {
from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">";
}
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
return false;
}
}
项目:JAVA-
文件:EmailSender.java
/**
* 设置发信人
*
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
if (from == null || from.trim().equals("")) {
from = PropertiesUtil.getString("email.send.from");
}
try {
String[] f = from.split(",");
if (f.length > 1) {
from = MimeUtility.encodeText(f[0]) + "<" + f[1] + ">";
}
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
logger.error(e.getLocalizedMessage());
return false;
}
}
项目:hermes
文件:DispositionNotification.java
private void saveReportValues() throws AS2MessageException {
try {
Enumeration reportEn = reportValues.getAllHeaderLines();
StringBuffer reportData = new StringBuffer();
while (reportEn.hasMoreElements()) {
reportData.append((String) reportEn.nextElement()).append("\r\n");
}
reportData.append("\r\n");
String reportText = MimeUtility.encodeText(reportData.toString(),
"us-ascii", "7bit");
reportPart.setContent(reportText,
AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
reportPart.setHeader("Content-Type",
AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
reportPart.setHeader("Content-Transfer-Encoding", "7bit");
}
catch (Exception e) {
throw new AS2MessageException("Error in saving report values", e);
}
}
项目:hermes
文件:DispositionNotification.java
private void saveReportValues() throws AS2MessageException {
try {
Enumeration reportEn = reportValues.getAllHeaderLines();
StringBuffer reportData = new StringBuffer();
while (reportEn.hasMoreElements()) {
reportData.append((String) reportEn.nextElement()).append("\r\n");
}
reportData.append("\r\n");
String reportText = MimeUtility.encodeText(reportData.toString(),
"us-ascii", "7bit");
reportPart.setContent(reportText,
AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
reportPart.setHeader("Content-Type",
AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
reportPart.setHeader("Content-Transfer-Encoding", "7bit");
}
catch (Exception e) {
throw new AS2MessageException("Error in saving report values", e);
}
}
项目:scada
文件:MailUtils.java
/**
* ����ʼ�������
* @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;
}
项目:nbone
文件:MailServiceImpl.java
/**
*
* 发送邮件时添加附件列表
* @param mp
* @param attachFiles
* @return
* @throws MailException
* @throws IOException
* @throws MessagingException
*/
private Multipart addAttachFile(Multipart mp, Set<String> attachFiles) throws MailException, IOException, MessagingException{
if(mp == null){
throw new MailException("bean Multipart is null .");
}
//没有附件时直接返回
if(attachFiles == null || (attachFiles.size())== 0){
return mp;
}
Iterator<String> iterator = attachFiles.iterator();
while (iterator.hasNext()) {
String fileName = iterator.next();
MimeBodyPart mbp_file = new MimeBodyPart();
mbp_file.attachFile(fileName);
mp.addBodyPart(mbp_file);
//防止乱码
String encode = MimeUtility.encodeText(mbp_file.getFileName());
mbp_file.setFileName(encode);
}
return mp;
}
项目:alimama
文件:POP3ReceiveMailTest.java
/**
* 获得邮件发件人
* @param msg 邮件内容
* @return 姓名 <Email地址>
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
String from = "";
Address[] froms = msg.getFrom();
if (froms.length < 1)
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;
}
项目:communote-server
文件:MailMessageHelper.java
/**
* Extracts the attachments from the mail.
*
* @param message
* The message.
* @return Collection of attachments as {@link AttachmentTO}.
* @throws IOException
* Exception.
* @throws MessagingException
* Exception.
*/
public static Collection<AttachmentTO> getAttachments(Message message)
throws MessagingException, IOException {
Collection<AttachmentTO> attachments = new ArrayList<AttachmentTO>();
Collection<Part> parts = getAllParts(message);
for (Part part : parts) {
String disposition = part.getDisposition();
String contentType = part.getContentType();
if (StringUtils.containsIgnoreCase(disposition, "inline")
|| StringUtils.containsIgnoreCase(disposition, "attachment")
|| StringUtils.containsIgnoreCase(contentType, "name=")) {
String fileName = part.getFileName();
Matcher matcher = FILENAME_PATTERN.matcher(part.getContentType());
if (matcher.matches()) {
fileName = matcher.group(1);
fileName = StringUtils.substringBeforeLast(fileName, ";");
}
if (StringUtils.isNotBlank(fileName)) {
fileName = fileName.replace("\"", "").replace("\\\"", "");
fileName = MimeUtility.decodeText(fileName);
if (fileName.endsWith("?=")) {
fileName = fileName.substring(0, fileName.length() - 2);
}
fileName = fileName.replace("?", "_");
AttachmentTO attachmentTO = new AttachmentStreamTO(part.getInputStream());
attachmentTO.setContentLength(part.getSize());
attachmentTO.setMetadata(new ContentMetadata());
attachmentTO.getMetadata().setFilename(fileName);
if (StringUtils.isNotBlank(contentType)) {
contentType = contentType.split(";")[0].toLowerCase();
}
attachmentTO.setStatus(AttachmentStatus.UPLOADED);
attachments.add(attachmentTO);
}
}
}
return attachments;
}
项目:Camel
文件:MimeMultipartDataFormat.java
private String getAttachmentKey(BodyPart bp) throws MessagingException, UnsupportedEncodingException {
// use the filename as key for the map
String key = bp.getFileName();
// if there is no file name we use the Content-ID header
if (key == null && bp instanceof MimeBodyPart) {
key = ((MimeBodyPart)bp).getContentID();
if (key != null && key.startsWith("<") && key.length() > 2) {
// strip <>
key = key.substring(1, key.length() - 1);
}
}
// or a generated content id
if (key == null) {
key = UUID.randomUUID().toString() + "@camel.apache.org";
}
return MimeUtility.decodeText(key);
}
项目:metasfresh
文件:Util.java
/***
* encode base64
*
* @param b
* @return
* @throws Exception
*/
// metas: 03749
public static byte[] encodeBase64(final byte[] b)
{
try
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final OutputStream b64os = MimeUtility.encode(baos, "base64");
b64os.write(b);
b64os.close();
return baos.toByteArray();
}
catch (Exception e)
{
throw new AdempiereException(e);
}
}
项目:metasfresh
文件:Util.java
/***
* decode base64
*
* @param b
* @return
* @throws Exception
*/
// metas: 03749
public static byte[] decodeBase64(byte[] b)
{
try
{
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
catch (Exception e)
{
throw new AdempiereException(e);
}
}
项目:Raven-Messenger
文件:MailControlAndroid.java
public static void receiveEmailPOPAndroid(MailProfile mailprofile, String folder, int offset, int limit) throws Exception{
Properties props = new Properties();
props.setProperty("mail.store.protocol", "pop3");
props.put("mail.pop3.port", mailprofile.getPop3Port());
props.setProperty("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback",
"false");
props.setProperty("mail.pop3.port", "" + mailprofile.getPop3Port());
props.setProperty("mail.pop3.socketFactory.port", ""
+ mailprofile.getPop3Port());
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect(mailprofile.getPop3Host(), mailprofile.getEmail(), mailprofile.getPassword());
Folder inbox = store.getFolder(folder);
inbox.open(Folder.READ_ONLY);
if(limit > inbox.getMessageCount()) limit = inbox.getMessageCount()-1;
javax.mail.Message[] msg = inbox.getMessages(inbox.getMessageCount()-offset-limit, inbox.getMessageCount()-offset);
String content = null;
javax.mail.Message m;
try{
for(int i=msg.length-1; i >= 0; i--){
m = msg[i];
Object msgContent = m.getContent();
if (msgContent instanceof Multipart) {
Multipart multipart = (Multipart) msgContent;
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) {
DataHandler handler = bodyPart.getDataHandler();
}
else {
if(bodyPart instanceof IMAPBodyPart){
content = ((IMAPBodyPart)bodyPart).getContent().toString(); // the changed code
if(((IMAPBodyPart)bodyPart).getContent() instanceof MimeMultipart){
Multipart multi2 = (Multipart) ((IMAPBodyPart)bodyPart).getContent();
for (int k = 0; k < multi2.getCount(); k++)
content =multi2.getBodyPart(k).getContent().toString();
}
}
}
}
}
else
content= m.getContent().toString();
if(m.getContentType().startsWith("com.sun.mail.util.BASE64DecoderStream"))
content = ((BASE64DecoderStream) m.getContent()).toString();
mailprofile.addReceivedMessage(
new Email(
MimeUtility.decodeText(m.getFrom()[0].toString()),
MimeUtility.decodeText(m.getAllRecipients()[0].toString()),
MimeUtility.decodeText(m.getSubject()), m.getReceivedDate(),
content,
new ArrayList<File>()
)
);
}
} catch(Exception e){}
finally{
if(inbox != null)
inbox.close(true);
if(store != null)
store.close();
}
}
项目:Raven-Messenger
文件:MailControlAndroid.java
public static void receiveEmailIMAPAndroid(MailProfile mailprofile, String folder, int offset, int limit) throws Exception{
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap.port", mailprofile.getImapPort());
props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback",
"false");
props.setProperty("mail.imap.port", "" + mailprofile.getImapPort());
props.setProperty("mail.imap.socketFactory.port", ""
+ mailprofile.getImapPort());
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect(mailprofile.getImapHost(), mailprofile.getEmail(), mailprofile.getPassword());
Folder inbox = store.getFolder(folder);
inbox.open(Folder.READ_ONLY);
if(limit > inbox.getMessageCount()) limit = inbox.getMessageCount()-1;
javax.mail.Message[] msg = inbox.getMessages(inbox.getMessageCount()-offset-limit, inbox.getMessageCount()-offset);
String content;
javax.mail.Message m;
try{
for(int i=msg.length-1; i >= 0; i--){
m = msg[i];
content = m.getContent().toString();
Object msgContent = m.getContent();
if (msgContent instanceof Multipart) {
Multipart multipart = (Multipart) msgContent;
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) {
DataHandler handler = bodyPart.getDataHandler();
}
else {
if(bodyPart instanceof IMAPBodyPart){
content = ((IMAPBodyPart)bodyPart).getContent().toString(); // the changed code
if(((IMAPBodyPart)bodyPart).getContent() instanceof MimeMultipart){
Multipart multi2 = (Multipart) ((IMAPBodyPart)bodyPart).getContent();
for (int k = 0; k < multi2.getCount(); k++)
content =multi2.getBodyPart(k).getContent().toString();
}
}
}
}
}
else
content= m.getContent().toString();
if(content.startsWith("com.sun.mail.util.BASE64DecoderStream")){
}
mailprofile.addReceivedMessage(
new Email(
MimeUtility.decodeText(m.getFrom()[0].toString()),
MimeUtility.decodeText(m.getAllRecipients()[0].toString()),
MimeUtility.decodeText(m.getSubject()), m.getReceivedDate(),
content,
new ArrayList<File>()
)
);
}
} catch(Exception e){e.printStackTrace();}
finally{
if(inbox != null)
inbox.close(true);
if(store != null)
store.close();
}
}
项目:daq-eclipse
文件:SMTPAppender.java
/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
public
void activateOptions() {
Session session = createSession();
msg = new MimeMessage(session);
try {
addressMessage(msg);
if(subject != null) {
try {
msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", null));
} catch(UnsupportedEncodingException ex) {
LogLog.error("Unable to encode SMTP subject", ex);
}
}
} catch(MessagingException e) {
LogLog.error("Could not activate SMTPAppender options.", e );
}
if (evaluator instanceof OptionHandler) {
((OptionHandler) evaluator).activateOptions();
}
}
项目:sakai
文件:BaseMailArchiveService.java
/**
* Access the from: address of the message.
*
* @return The from: address of the message.
*/
public String getFromAddress()
{
String fromAddress = ((m_fromAddress == null) ? "" : m_fromAddress);
try
{
fromAddress = MimeUtility.decodeText(fromAddress);
}
catch (UnsupportedEncodingException e)
{
// if unable to decode RFC address, just return address as is
log.debug(this+".getFromAddress "+e.toString());
}
return fromAddress;
}
项目:LNTUOnline-API
文件:Mail.java
public static boolean sendAndCc(String smtp, String from, String to, String copyto,
String subject, String content, String username, String password) throws UnsupportedEncodingException {
Mail theMail = new Mail(smtp);
theMail.setNeedAuth(true); // 验证
if (!theMail.setSubject(MimeUtility.encodeText(subject,MimeUtility.mimeCharset("gb2312"),null)))
return false;
if (!theMail.setBody(content))
return false;
if (!theMail.setTo(to))
return false;
if (!theMail.setCopyTo(copyto))
return false;
if (!theMail.setFrom(from))
return false;
theMail.setNamePass(username, password);
if (!theMail.sendOut())
return false;
return true;
}
项目:Genji
文件:MailReader.java
private static void handleAttachment(Part part, List<EmailAttachment> attachments) throws MessagingException {
String fileName = part.getFileName();
try {
if (fileName != null) {
fileName = MimeUtility.decodeText(fileName);
} else {
fileName = "binaryPart.dat";
}
attachments.add(createEmailAttachment(part, fileName));
} catch (Exception e) {
// just ignore
}
}
项目:smtp-sender
文件:Rfc2074MenuItem.java
private ActionListener createDecodeAction() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
try {
String encodeText = StringUtils.defaultIfEmpty(Rfc2074Dialog.this.encodeTextArea.getText(), "");
String decodeText = encodeText;
if (encodeText.startsWith("=?")) {
decodeText = MimeUtility.decodeWord(encodeText);
}
Rfc2074Dialog.this.decodeTextArea.setText(decodeText);
} catch (Throwable e) {
JOptionPane.showMessageDialog(Rfc2074Dialog.this, e.getClass().getSimpleName() + " - " + e.getMessage(), "Decoding fail !", JOptionPane.ERROR_MESSAGE);
}
}
};
}
项目:translationstudio8
文件:MessageParser.java
/**
* 获取消息附件中的文件.
* @return List<ResourceFileBean>
* 文件的集合(每个 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;
}
项目:community-edition-old
文件:SubethaEmailMessage.java
/**
* 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;
}
项目:community-edition-old
文件:ContentModelMessage.java
/**
* This method builds {@link MimeMessage} based on {@link ContentModel}
*
* @throws MessagingException
*/
private void buildContentModelMessage() throws MessagingException
{
Map<QName, Serializable> properties = messageFileInfo.getProperties();
String prop = null;
setSentDate(messageFileInfo.getModifiedDate());
// Add FROM address
Address[] addressList = buildSenderFromAddress();
addFrom(addressList);
// Add TO address
addressList = buildRecipientToAddress();
addRecipients(RecipientType.TO, addressList);
prop = (String) properties.get(ContentModel.PROP_TITLE);
try
{
prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop;
prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null);
}
catch (UnsupportedEncodingException e)
{
// ignore
}
setSubject(prop);
setContent(buildContentModelMultipart());
}
项目:SelfSoftShop
文件:MailServiceImpl.java
public void sendMail(String subject, String templatePath, Map<String, Object> data, String toMail) {
try {
Setting setting = SettingUtil.getSetting();
JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl)javaMailSender;
javaMailSenderImpl.setHost(setting.getSmtpHost());
javaMailSenderImpl.setPort(setting.getSmtpPort());
javaMailSenderImpl.setUsername(setting.getSmtpUsername());
javaMailSenderImpl.setPassword(setting.getSmtpPassword());
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
Configuration configuration = freemarkerManager.getConfiguration(servletContext);
Template template = configuration.getTemplate(templatePath);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getShopName()) + " <" + setting.getSmtpFromMail() + ">");
mimeMessageHelper.setTo(toMail);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(text, true);
addSendMailTask(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
项目:geokettle-2.0
文件:JobEntryGetPOP.java
public static void handlePart(String foldername, Part part) throws MessagingException, IOException
{
String disposition = part.getDisposition();
// String contentType = part.getContentType();
if ((disposition != null)
&& (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)))
{
saveFile(foldername, MimeUtility.decodeText(part.getFileName()), part.getInputStream());
}
}
项目:sakai
文件:BaseMailArchiveService.java
/**
* Access the from: address of the message.
*
* @return The from: address of the message.
*/
public String getFromAddress()
{
String fromAddress = ((m_fromAddress == null) ? "" : m_fromAddress);
try
{
fromAddress = MimeUtility.decodeText(fromAddress);
}
catch (UnsupportedEncodingException e)
{
// if unable to decode RFC address, just return address as is
log.debug(this+".getFromAddress "+e.toString());
}
return fromAddress;
}
项目:jcabi-email
文件:StSubject.java
@Override
public void attach(final Message message) throws MessagingException {
if (this.subject == null) {
throw new IllegalArgumentException(
"Email subject can't be NULL"
);
}
if (this.charset == null) {
throw new IllegalArgumentException(
"Subject charset can't be NULL"
);
}
try {
message.setSubject(
MimeUtility.encodeText(this.subject, this.charset, "Q")
);
} catch (final UnsupportedEncodingException ex) {
throw new IllegalStateException(ex);
}
}
项目:jcabi-email
文件:EnHtml.java
@Override
public MimeBodyPart part() throws MessagingException {
if (this.text == null) {
throw new IllegalArgumentException(
"Attachment text can't be NULL"
);
}
if (this.charset == null) {
throw new IllegalArgumentException(
"Attachment charset can't be NULL"
);
}
final MimeBodyPart mime = new MimeBodyPart();
final String characterset = MimeUtility.quote(
this.charset,
"()<>@,;:\\\"\t []/?="
);
final String ctype = String.format(
"text/html;charset=\"%s\"",
characterset
);
mime.setContent(this.text, ctype);
mime.addHeader("Content-Type", ctype);
return mime;
}
项目:cs-actions
文件:GetMailMessage.java
protected Map<String, String> getMessageByContentTypes(Message message, String characterSet) throws Exception {
Map<String, String> messageMap = new HashMap<>();
if (message.isMimeType(TEXT_PLAIN)) {
messageMap.put(TEXT_PLAIN, MimeUtility.decodeText(message.getContent().toString()));
} else if (message.isMimeType(TEXT_HTML)) {
messageMap.put(TEXT_HTML, MimeUtility.decodeText(convertMessage(message.getContent().toString())));
} else if (message.isMimeType(MULTIPART_MIXED) || message.isMimeType(MULTIPART_RELATED)) {
messageMap.put(MULTIPART_MIXED, extractMultipartMixedMessage(message, characterSet));
} else {
Object obj = message.getContent();
Multipart mpart = (Multipart) obj;
for (int i = 0, n = mpart.getCount(); i < n; i++) {
Part part = mpart.getBodyPart(i);
if (decryptMessage && part.getContentType() != null &&
part.getContentType().equals(ENCRYPTED_CONTENT_TYPE)) {
part = decryptPart((MimeBodyPart)part);
}
String disposition = part.getDisposition();
String partContentType = part.getContentType().substring(0, part.getContentType().indexOf(";"));
if (disposition == null) {
if (part.getContent() instanceof MimeMultipart) {
// multipart with attachment
MimeMultipart mm = (MimeMultipart) part.getContent();
for (int j = 0; j < mm.getCount(); j++) {
if (mm.getBodyPart(j).getContent() instanceof String) {
BodyPart bodyPart = mm.getBodyPart(j);
if ((characterSet != null) && (characterSet.trim().length() > 0)) {
String contentType = bodyPart.getHeader(CONTENT_TYPE)[0];
contentType = contentType
.replace(contentType.substring(contentType.indexOf("=") + 1), characterSet);
bodyPart.setHeader(CONTENT_TYPE, contentType);
}
String partContentType1 = bodyPart
.getContentType().substring(0, bodyPart.getContentType().indexOf(";"));
messageMap.put(partContentType1,
MimeUtility.decodeText(bodyPart.getContent().toString()));
}
}
} else {
//multipart - w/o attachment
//if the user has specified a certain characterSet we decode his way
if ((characterSet != null) && (characterSet.trim().length() > 0)) {
InputStream istream = part.getInputStream();
ByteArrayInputStream bis = new ByteArrayInputStream(ASCIIUtility.getBytes(istream));
int count = bis.available();
byte[] bytes = new byte[count];
count = bis.read(bytes, 0, count);
messageMap.put(partContentType,
MimeUtility.decodeText(new String(bytes, 0, count, characterSet)));
} else {
messageMap.put(partContentType, MimeUtility.decodeText(part.getContent().toString()));
}
}
}
} //for
} //else
return messageMap;
}
项目:cs-actions
文件:GetMailMessageTest.java
/**
* Test execute method throws UnsupportedEncodingException.
*
* @throws Exception
*/
@Test
public void testExecuteUnsupportedEncodingException() throws Exception {
doReturn(messageMock).when(getMailMessageSpy).getMessage();
doNothing().when(messageMock).setFlag(Flags.Flag.DELETED, true);
doReturn(new String[]{"1"}).when(messageMock).getHeader(anyString());
doReturn(SUBJECT_TEST).when(getMailMessageSpy).changeHeaderCharset("1", CHARACTERSET);
PowerMockito.mockStatic(MimeUtility.class);
PowerMockito.doThrow(new UnsupportedEncodingException("")).when(MimeUtility.class, "decodeText", anyString());
addRequiredInputs();
inputs.setSubjectOnly("");
inputs.setCharacterSet(BAD_CHARACTERSET);
exception.expect(Exception.class);
exception.expectMessage("The given encoding (" + BAD_CHARACTERSET + ") is invalid or not supported.");
getMailMessageSpy.execute(inputs);
}
项目:yako
文件:SimpleEmailMessageProvider.java
/**
* Returns an attachment list for a given Mime Multipart object.
*
* @param mp the input Mime part of the email's content
* @param level debug variable
* @return list of files where the attachments are saved
* @throws MessagingException
* @throws IOException
*/
private List<Attachment> getAttachmentsOfMultipartMessage(Multipart mp, boolean onlyInfo, int level) throws MessagingException, IOException {
List<Attachment> files = new LinkedList<Attachment>();
for (int j = 0; j < mp.getCount(); j++) {
Part bp = mp.getBodyPart(j);
String contentType = bp.getContentType().toLowerCase();
if (!Part.ATTACHMENT.equalsIgnoreCase(bp.getDisposition())) {
if (contentType.indexOf("multipart/") != -1) {
files.addAll(getAttachmentsOfMultipartMessage((Multipart)(bp.getContent()), onlyInfo, level + 1));
}
continue;
}
String fName = bp.getFileName() == null ? "noname" : bp.getFileName();
files.add(new Attachment(MimeUtility.decodeText(fName), bp.getSize()));
if (!onlyInfo) {
InputStream is = bp.getInputStream();
File f = new File(this.attachmentFolder + bp.getFileName());
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[4096];
int bytesRead;
while((bytesRead = is.read(buf))!=-1) {
fos.write(buf, 0, bytesRead);
}
fos.close();
}
}
return files;
}