下面列出了怎么用javax.mail.BodyPart的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param mimeMultipart
* @return
* @throws MessagingException
* @throws IOException
*/
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
final StringBuilder result = new StringBuilder();
final int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
final BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result.append("\n");
result.append(bodyPart.getContent());
} else if (bodyPart.isMimeType("text/html")) {
result.append("\n");
result.append((String) bodyPart.getContent());
} else if (bodyPart.getContent() instanceof MimeMultipart) {
result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
}
}
return result.toString();
}
/**
* Check if the body is from the content type and returns it if not attachment
*
* @param mimePart
* @param contentType
* @return null if not with specific content type or part is attachment
*/
private String getBodyIfNotAttachment(
BodyPart mimePart,
String contentType ) throws MessagingException, IOException {
String mimePartContentType = mimePart.getContentType().toLowerCase();
if (mimePartContentType.startsWith(contentType)) { // found a part with given mime type
String contentDisposition = mimePart.getDisposition();
if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) {
Object partContent = mimePart.getContent();
if (partContent instanceof InputStream) {
return IoUtils.streamToString((InputStream) partContent);
} else {
return partContent.toString();
}
}
}
return null;
}
/** Adds a plain text attachment
* @param BodyPart
*/
private void addPlainTextAttachment(BodyPart b)
{
try
{
System.out.println("Adding plain text attachment");
String fileName = getFileName(b.getContentType());
String content = (String) b.getContent();
int size = b.getSize();
Attachment attach = new Attachment(fileName, content.getBytes(), size);
attachments.add(attach);
}
catch (MessagingException | IOException e)
{
System.err.println("Could not get file name or read file content");
e.printStackTrace();
}
}
private static Multipart getMessagePart() throws MessagingException, IOException {
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(getVal("msg.Body"));
multipart.addBodyPart(messageBodyPart);
if (getBoolVal("attach.reports")) {
LOG.info("Attaching Reports as zip");
multipart.addBodyPart(getReportsBodyPart());
} else {
if (getBoolVal("attach.standaloneHtml")) {
multipart.addBodyPart(getStandaloneHtmlBodyPart());
}
if (getBoolVal("attach.console")) {
multipart.addBodyPart(getConsoleBodyPart());
}
if (getBoolVal("attach.screenshots")) {
multipart.addBodyPart(getScreenShotsBodyPart());
}
}
messageBodyPart.setContent(getVal("msg.Body")
.concat("\n\n\n")
.concat(MailComponent.getHTMLBody()), "text/html");
return multipart;
}
private static String getBodyPart(MimeMultipart mimeMultiPart) throws IOException, MessagingException
{
for(int i=0; i<mimeMultiPart.getCount(); i++)
{
BodyPart bodyPart = mimeMultiPart.getBodyPart(i);
if(bodyPart.isMimeType("text/plain"))
{
return (String) bodyPart.getContent();
}
else if(bodyPart.getContent() instanceof MimeMultipart)
{
return getBodyPart((MimeMultipart)bodyPart.getContent());
}
}
return "";
}
private List<String> getBodyText(Part part) throws MessagingException, IOException {
Object c = part.getContent();
if (c instanceof String) {
return UtilMisc.toList((String) c);
} else if (c instanceof Multipart) {
List<String> textContent = new ArrayList<>(); // SCIPIO: switched to ArrayList
int count = ((Multipart) c).getCount();
for (int i = 0; i < count; i++) {
BodyPart bp = ((Multipart) c).getBodyPart(i);
textContent.addAll(this.getBodyText(bp));
}
return textContent;
} else {
return new ArrayList<>(); // SCIPIO: switched to ArrayList
}
}
protected static void processMessageContent(Message message, Mail mail) throws MessagingException, IOException {
if (isMultipartMessage(message)) {
Multipart multipart = (Multipart) message.getContent();
int numberOfParts = multipart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
BodyPart bodyPart = multipart.getBodyPart(partCount);
processMessagePartContent(bodyPart, mail);
}
} else {
processMessagePartContent(message, mail);
}
}
/**
* ����ʼ��ı�����
* @param part �ʼ���
* @param content �洢�ʼ��ı����ݵ��ַ���
*/
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
//������ı����͵ĸ�����ͨ��getContent��������ȡ���ı����ݣ����ⲻ��������Ҫ�Ľ��������������Ҫ���ж�
boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
if (part.isMimeType("text/*") && !isContainTextAttach) {
content.append(part.getContent().toString());
} else if (part.isMimeType("message/rfc822")) {
getMailTextContent((Part)part.getContent(),content);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
getMailTextContent(bodyPart,content);
}
}
}
private void sendAndCc(String from, String to, String copyto,
String subject, String content) throws AddressException,
MessagingException {
props.put("mail.smtp.host", smtp);
props.put("mail.smtp.auth", "true");
mimeMessage.setSubject(subject);
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent("" + content, "text/html;charset=GBK");
multipart.addBodyPart(bodyPart);
mimeMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
mimeMessage.setRecipients(Message.RecipientType.CC,
(Address[]) InternetAddress.parse(copyto));
mimeMessage.setFrom(new InternetAddress(from));
sendOut();
}
protected MimeMessage format(Reader reader, PropertiesSubstitutor ps) throws MessagingException, IOException {
//Read message body content
String text = ps.substitute(reader);
//Create message and set headers
MimeMessage message = new MimeMessage(session);
message.setFrom(InternetAddress.getLocalAddress(session));
if (subject != null) {
message.setSubject(ps.substitute(subject));
}
//if html content
if (TYPE_HTML.equalsIgnoreCase(type)) {
BodyPart body = new MimeBodyPart();
body.setContent(text, "text/html");
Multipart mp = new MimeMultipart("related");
mp.addBodyPart(body);
message.setContent(mp);
} else {
message.setText(text);
}
return message;
}
/**
* Extract the text content for a {@link BodyPart}, assuming the default
* encoding.
*/
public static String getTextContent(BodyPart part) throws MessagingException, IOException {
ContentType contentType = new ContentType(part.getContentType());
String charset = contentType.getParameter("charset");
if (charset == null) {
// N.B.(schwardo): The MIME spec doesn't seem to provide a
// default charset, but the default charset for HTTP is
// ISO-8859-1. That seems like a reasonable default.
charset = "ISO-8859-1";
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteStreams.copy(part.getInputStream(), baos);
try {
return new String(baos.toByteArray(), charset);
} catch (UnsupportedEncodingException ex) {
return new String(baos.toByteArray());
}
}
/**
* Retrieve message from retriever and check the attachment and text content
*
* @param server Server to read from
* @param to Account to retrieve
*/
private void retrieveAndCheck(AbstractServer server, String to) throws MessagingException, IOException {
try (Retriever retriever = new Retriever(server)) {
Message[] messages = retriever.getMessages(to);
assertEquals(1, messages.length);
Message message = messages[0];
assertTrue(message.getContentType().startsWith("multipart/mixed"));
MimeMultipart body = (MimeMultipart) message.getContent();
assertTrue(body.getContentType().startsWith("multipart/mixed"));
assertEquals(2, body.getCount());
// Message text
final BodyPart textPart = body.getBodyPart(0);
String text = (String) textPart.getContent();
assertEquals(createLargeString(), text);
final BodyPart attachment = body.getBodyPart(1);
assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file"));
InputStream attachmentStream = (InputStream) attachment.getContent();
byte[] bytes = IOUtils.toByteArray(attachmentStream);
assertArrayEquals(createLargeByteArray(), bytes);
}
}
public void sendMail(String to, String from, String subject, String text) {
Session session = Session.getDefaultInstance(setupSmtpProperties());
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html");
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(messageBodyPart);
message.setContent(mimeMultipart);
Transport.send(message);
} catch (MessagingException e) {
logger.error("Could not send mail", e);
}
}
@Test
public void testAttachment() throws Exception {
MailMessage message = new MailMessage();
MailAttachment attachment = MailAttachment.create();
attachment.setContentType("application/x-something")
.setData(Buffer.buffer("***"))
.setDescription("description")
.setDisposition("attachment")
.setName("file.txt");
message.setAttachment(attachment);
String mime = new MailEncoder(message, HOSTNAME).encode();
assertThat(mime, containsString("Content-Type: application/x-something; name=\"file.txt\""));
assertThat(mime, containsString("Content-Description: description"));
assertThat(mime, containsString("Content-Disposition: attachment; filename=\"file.txt\""));
BodyPart part = ((MimeMultipart) TestUtils.getMessage(mime).getContent()).getBodyPart(0);
assertEquals("***", TestUtils.inputStreamToString(part.getInputStream()));
assertEquals("attachment", part.getDisposition());
assertEquals("file.txt", part.getFileName());
assertEquals("description", part.getDescription());
assertEquals("application/x-something; name=\"file.txt\"", part.getContentType());
}
private static void assertEquals(ExpectedAttachment expected, BodyPart attachment, AssertionRegistry registry) throws Exception {
// @formatter:off
String prefix = "attachment named '" + expected.getName() + "'" + (attachment==null ? " (/!\\ not found)" : "");
String contentType = attachment == null || attachment.getContentType()==null ? null : attachment.getContentType();
registry.register(() -> Assert.assertTrue(prefix + " mimetype should match '" + expected.getMimetype() + "' but was " + (contentType==null ? "null" : "'" + contentType + "'"),
contentType!=null && expected.getMimetype().matcher(contentType).matches()));
registry.register(() -> Assert.assertEquals(prefix + " description should be '" + expected.getDescription() + "'",
expected.getDescription(),
attachment == null ? null : attachment.getDescription()));
registry.register(() -> Assert.assertEquals(prefix + " disposition should be '" + expected.getDisposition() + "'",
expected.getDisposition(),
attachment == null ? null : attachment.getDisposition()));
registry.register(() -> Assert.assertArrayEquals(prefix + " has invalid content",
expected.getContent(),
attachment == null ? null : getContent(attachment)));
// @formatter:on
}
/**
* Send a calendar message.
*
* @param mail
* The mail to send
* @param transport
* the smtp transport object
* @param session
* the smtp session object
* @throws AddressException
* If invalid address
* @throws SendFailedException
* If an error occurred during sending
* @throws MessagingException
* If a messaging error occurred
*/
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
Message msg = prepareMessage( mail, session );
msg.setHeader( HEADER_NAME, HEADER_VALUE );
MimeMultipart multipart = new MimeMultipart( );
BodyPart msgBodyPart = new MimeBodyPart( );
msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );
multipart.addBodyPart( msgBodyPart );
BodyPart calendarBodyPart = new MimeBodyPart( );
calendarBodyPart.setContent( mail.getCalendarMessage( ),
AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
+ AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
+ AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
multipart.addBodyPart( calendarBodyPart );
msg.setContent( multipart );
sendMessage( msg, transport );
}
private String getBodyPartFileName (BodyPart bodyPart) throws Exception{
String partName = null;
String[] headers = bodyPart.getHeader(BaseController.PARAMETRO_CONTENT_DISPOSITION);
if(headers != null && headers.length > 0){
String header = headers[0];
// in due parti perche il suffisso con solo " imbrogliava il controllo
int prefixIndex = header.indexOf(BaseController.PREFIX_FILENAME);
if(prefixIndex > -1){
partName = header.substring(prefixIndex + BaseController.PREFIX_FILENAME.length());
int suffixIndex = partName.indexOf(BaseController.SUFFIX_FILENAME);
partName = partName.substring(0,suffixIndex);
}
}
return partName;
}
private void addPartContent(BodyPart bodyPart, Mail mail, String fileName, AttributeName attributeName) throws IOException, MessagingException {
ImmutableMap.Builder<String, byte[]> fileNamesToPartContent = AttributeUtils
.getValueAndCastFromMail(mail, attributeName, MAP_STRING_BYTES_CLASS)
.map(ImmutableMap.<String, byte[]>builder()::putAll)
.orElse(ImmutableMap.builder());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bodyPart.writeTo(new BufferedOutputStream(byteArrayOutputStream));
fileNamesToPartContent.put(fileName, byteArrayOutputStream.toByteArray());
mail.setAttribute(new Attribute(attributeName, AttributeValue.ofAny(fileNamesToPartContent.build())));
}
@Test
public void isMdnSentAutomaticallyShouldDetectBigMDN() throws Exception {
MimeMessage message = MimeMessageUtil.defaultMimeMessage();
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart scriptPart = new MimeBodyPart();
scriptPart.setDataHandler(
new DataHandler(
new ByteArrayDataSource(
Joiner.on("\r\n").join(
"Final-Recipient: rfc822;[email protected]",
"Disposition: automatic-action/MDN-sent-automatically; displayed",
""),
"message/disposition-notification;")
));
scriptPart.setHeader("Content-Type", "message/disposition-notification");
BodyPart bigBody = MimeMessageBuilder.bodyPartBuilder() // ~3MB
.data("12345678\r\n".repeat(300 * 1024))
.build();
multipart.addBodyPart(bigBody);
multipart.addBodyPart(scriptPart);
message.setContent(multipart);
message.saveChanges();
FakeMail fakeMail = FakeMail.builder()
.name("mail")
.sender(MailAddressFixture.ANY_AT_JAMES)
.mimeMessage(message)
.build();
assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
private static void addAttachment(BodyPart bp, EMail email)
throws UnsupportedEncodingException, MessagingException {
// Skip part without a filename
if (StringUtils.isEmpty(bp.getFileName()))
return;
// Skip part that is not an attachment
String[] values = bp.getHeader("Content-Disposition");
String disposition = "";
if (values != null && values.length > 0)
disposition = new ContentDisposition(values[0]).getDisposition();
if (!disposition.contains("attachment"))
return;
String name = MimeUtility.decodeText(bp.getFileName());
String fileName = FilenameUtils.getName(name);
EMailAttachment attachment = new EMailAttachment();
attachment.setFileName(fileName);
attachment.setMimeType(bp.getContentType());
attachment.setSize(bp.getSize());
try (InputStream is = bp.getInputStream()) {
byte[] bytes = IOUtils.toByteArray(is);
attachment.setData(bytes);
attachment.setSize(bytes.length);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
email.addAttachment(attachment);
}
private String getAttachment(String name, MimeMultipart multipart) throws IOException, MessagingException {
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getFileName() != null && bodyPart.getFileName().equalsIgnoreCase(name)) {
assertThat(bodyPart.getContentType()).startsWith(TEXT_CONTENT_TYPE);
return read(bodyPart);
}
}
return null;
}
/**
* Extract the form name from the Content-Disposition in a
* multipart/form-data request.
*/
public static String getFieldName(BodyPart part) throws MessagingException {
String[] values = part.getHeader("Content-Disposition");
String name = null;
if (values != null && values.length > 0) {
name = new ContentDisposition(values[0]).getParameter("name");
}
return (name != null) ? name : "unknown";
}
private BodyPart sanitize(BodyPart bodyPart) throws MessagingException {
if (needsSanitizing(bodyPart)) {
if (bodyPart instanceof MimeBodyPart) {
MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;
mimeBodyPart.setText(
computeBodyFromOriginalCalendar(bodyPart),
StandardCharsets.UTF_8.name(),
bodyPart.getContentType().substring(TEXT_PREFIX_SIZE));
setFileNameIfNeeded(mimeBodyPart);
}
}
return bodyPart;
}
private List<String> getContentTypesFromMimeMultipart(
MimeMultipart mimeMultipart) throws MessagingException, IOException {
List<String> types = new ArrayList<>();
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.getContent() instanceof MimeMultipart) {
types.addAll(getContentTypesFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
} else {
types.add(bodyPart.getContentType());
}
}
return types;
}
private void storeBodyPartAsFile(BodyPart bodyPart, Mail mail, String fileName) throws Exception {
if (directoryName != null) {
saveAttachmentToFile(bodyPart, Optional.of(fileName)).ifPresent(filename ->
addFilenameToAttribute(mail, AttributeValue.of(filename), SAVED_ATTACHMENTS)
);
}
}
private static String getPlainTextFromMultipart(Multipart multipart) throws MessagingException, IOException {
StringBuilder result = new StringBuilder();
int count = multipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.isMimeType(TEXT_PLAIN)) {
result.append(NEW_LINE)
.append(bodyPart.getContent());
break; // without break same text can appear twice
} else if (bodyPart.isMimeType(TEXT_HTML)) {
result.append(NEW_LINE)
.append(Jsoup.parse((String) bodyPart.getContent()).text());
break; // without break same text can appear twice
} else if (bodyPart.isMimeType("application/pgp-encrypted")) {
//
// Body is encrypted so flag as such to enable easy understanding for users
//
result.append(NEW_LINE)
.append("<pgp encrypted text>")
.append(NEW_LINE)
.append(bodyPart.getContent().toString());
} else if (bodyPart.getContent() instanceof MimeMultipart){
result.append(NEW_LINE)
.append(getPlainTextFromMultipart((MimeMultipart) bodyPart.getContent()));
}
}
return result.toString();
}
/** 发送用户验证的邮件 */
public static void sendAccountActiveEmail(User user) {
String subject = "sdudoc邮箱验证提醒";
String content = "感谢您于" + DocUtil.getDateTime() + "在sdudoc注册,复制以下链接,即可完成安全验证:"
+ "http://127.0.0.1:8080/sdudoc/activeUser.action?user.username=" + user.getUsername()
+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
+ "若您没有申请过验证邮箱 ,请您忽略此邮件,由此给您带来的不便请谅解。";
// session.setDebug(true);
String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
Session session = getMailSession();
// 定义message
MimeMessage message = new MimeMessage(session);
try {
// 设定发送邮件的地址
message.setFrom(new InternetAddress(from));
// 设定接受邮件的地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
// 设定邮件主题
message.setSubject(subject);
// 设定邮件内容
BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
mdp.setContent(content, "text/html;charset=utf8");// 给BodyPart对象设置内容和格式/编码方式
Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
// 象(事实上可以存放多个)
mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
message.setContent(mm);// 把mm作为消息对象的内容
// message.setText(content);
message.saveChanges();
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean send(List<String> recipients,String from,String subject,List<BodyPart> parts){
MimeMultipart content=new MimeMultipart();
try{
for(BodyPart p : parts){
content.addBodyPart(p);
}
return send(recipients, from, subject, content);
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
public void addAttachment(String filename) throws Exception
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
public boolean send(List<String> recipients,String from,String subject,Object message,String mimeType){
String charset;
if(mimeType!=null){
Matcher m=charsetPattern.matcher(mimeType);
if(m.find()){
charset=m.group(1).toUpperCase();
}
else {
charset=defaultCharset;
mimeType+="; charset="+defaultCharset.toLowerCase();
}
}
else {
charset=defaultCharset;
mimeType=defaultContentType+"; charset="+defaultCharset.toLowerCase();
}
try{
MimeBodyPart mimeBody=new MimeBodyPart();
mimeBody.setContent(message, mimeType);
ArrayList<BodyPart> parts=new ArrayList<BodyPart>();
parts.add(mimeBody);
return send(recipients, from, subject, parts);
// byte[] content=message.getBytes(charset);
// return send(recipients, from, subject, content, mimeType);
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
/* catch(UnsupportedEncodingException uee){
logging.warn("Couldn't send email, unsupported encoding "+charset,uee);
return false;
}*/
}