use of javax.mail.internet.MimeBodyPart in project Axe by DongyuCai.
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;
}
use of javax.mail.internet.MimeBodyPart in project jdk8u_jdk by JetBrains.
the class MailTest method sendMail.
void sendMail() {
try {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, to);
message.setSubject("this is a multipart test");
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("please send also this Content\n ciao!");
multipart.addBodyPart(messageBodyPart1);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setContent("<b>please</b> send also this Content <br>ciao!", "text/html; charset=UTF-8");
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
/*
Transport tr = session.getTransport("smtp");
tr.connect(host,user, password);
tr.sendMessage(message,InternetAddress.parse(to));
tr.close();
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
String output = baos.toString();
System.out.println("output = " + output);
if (output.contains("also this Content")) {
System.out.println("Test PASSED.");
} else {
System.out.println("Test FAILED, missing content.");
throw new IllegalStateException("Test FAILED, missing content.");
}
} catch (MessagingException ignored) {
} catch (IOException ignored) {
}
}
use of javax.mail.internet.MimeBodyPart in project opennms by OpenNMS.
the class JavaMailer2 method createFileAttachment.
/*
public Message buildMessage(String m_charSet, String m_encoding, String m_contentType) throws JavaMailerException {
try {
String encodedText = MimeUtility.encodeText(getMessageText(), m_charSet, m_encoding);
if (getFileName() == null) {
message.setContent(encodedText, m_contentType+"; charset="+m_charSet);
} else {
BodyPart bp = new MimeBodyPart();
bp.setContent(encodedText, m_contentType+"; charset="+m_charSet);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(bp);
mp = new MimeMultipart();
mp.addBodyPart(createFileAttachment(new File(getFileName())));
message.setContent(mp);
}
message.setHeader("X-Mailer", getMailer());
message.setSentDate(new Date());
message.saveChanges();
return message;
} catch (AddressException e) {
log().error("Java Mailer Addressing exception: ", e);
throw new JavaMailerException("Java Mailer Addressing exception: ", e);
} catch (MessagingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer messaging exception: ", e);
} catch (UnsupportedEncodingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer encoding exception: ", e);
}
}
*/
/**
* Create a file attachment as a MimeBodyPart, checking to see if the file
* exists before we create the attachment.
*
* @param file file to attach
* @return attachment body part
* @throws javax.mail.MessagingException if we can't set the data handler or
* the file name on the MimeBodyPart
* @throws org.opennms.javamail.JavaMailerException if the file does not exist or is not
* readable
*/
public MimeBodyPart createFileAttachment(final File file) throws MessagingException, JavaMailerException {
if (!file.exists()) {
LOG.error("File attachment '{}' does not exist.", file.getAbsolutePath());
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' does not exist.");
}
if (!file.canRead()) {
LOG.error("File attachment '{}' is not readable.", file.getAbsolutePath());
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' is not readable.");
}
MimeBodyPart bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
return bodyPart;
}
use of javax.mail.internet.MimeBodyPart in project opennms by OpenNMS.
the class JavaMailAckReaderIT method workingWithMultiPartMessages.
/**
* tests the ability to create acknowledgments from an email for a multi-part text. This test
* creates a message from scratch rather than reading from an inbox. This message creation
* may not actually represent what comes from a mail server.
*/
@Test
public void workingWithMultiPartMessages() throws JavaMailerException, MessagingException {
List<Message> msgs = new ArrayList<Message>();
Properties props = new Properties();
Message msg = new MimeMessage(Session.getDefaultInstance(props));
Address[] addrs = new Address[1];
addrs[0] = new InternetAddress("david@opennms.org");
msg.addFrom(addrs);
msg.addRecipient(RecipientType.TO, new InternetAddress("david@opennms.org"));
msg.setSubject("Re: Notice #1234 JavaMailReaderImplTest Test Message");
Multipart mpContent = new MimeMultipart();
BodyPart textBp = new MimeBodyPart();
BodyPart htmlBp = new MimeBodyPart();
textBp.setText("ack");
htmlBp.setContent("<html>\n" + " <head>\n" + " <title>\n" + " Acknowledge\n" + " </title>\n" + " </head>\n" + " <body>\n" + " <h1>\n" + " ack\n" + " </h1>\n" + " </body>\n" + "</html>", "text/html");
mpContent.addBodyPart(textBp);
mpContent.addBodyPart(htmlBp);
msg.setContent(mpContent);
msgs.add(msg);
List<OnmsAcknowledgment> acks = m_processor.createAcks(msgs);
Assert.assertEquals(1, acks.size());
Assert.assertEquals(AckType.NOTIFICATION, acks.get(0).getAckType());
Assert.assertEquals("david@opennms.org", acks.get(0).getAckUser());
Assert.assertEquals(AckAction.ACKNOWLEDGE, acks.get(0).getAckAction());
Assert.assertEquals(new Integer(1234), acks.get(0).getRefId());
}
use of javax.mail.internet.MimeBodyPart in project Xponents by OpenSextant.
the class MessageConverter method parseMessage.
/**
* This is a recursive parser that pulls off attachments into Child content or saves plain text as main message text.
* Calendar invites are ignored.
*
* @param bodyPart individual sub-part to append to buffer
* @param parent parent doc
* @param buf text to append
* @param msgPrefixId msgId prefix
* @throws IOException on error
*/
public void parseMessage(Part bodyPart, ConvertedDocument parent, StringBuilder buf, String msgPrefixId) throws IOException {
InputStream partIO = null;
++attachmentNumber;
try {
PartMetadata meta = new PartMetadata(bodyPart);
//String charset = (meta.charset == null ? "UTF-8" : meta.charset);
textEncodings.add(meta.charset);
String filename = bodyPart.getFileName();
String fileext = meta.getPossibleFileExtension();
if (filename != null) {
fileext = FilenameUtils.getExtension(filename);
logger.debug("original filename: " + filename);
}
boolean hasExtension = StringUtils.isNotBlank(fileext);
if (!hasExtension) {
logger.debug("Unknown message part");
fileext = "dat";
}
if (filename == null && attachmentNumber > 1) {
filename = String.format("%s-Att%d.%s", msgPrefixId, attachmentNumber, fileext);
}
logger.debug("Charset for part is {}", meta.charset);
// IGNORE types: calendar.
if (meta.isCalendar()) {
logger.debug("{}# Ignore item", msgPrefixId);
return;
}
if (meta.isHTML()) {
//
logger.debug("{}# Save HTML part as its own file", msgPrefixId);
} else if (bodyPart.isMimeType("multipart/*")) {
Multipart mp = (Multipart) bodyPart.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
// This step does not actually save any content, it calls
// itself to continue to break down the parts into the
// finest grained elements, at which point
parseMessage(mp.getBodyPart(i), parent, buf, msgPrefixId);
}
// Exit point
return;
} else if (bodyPart.isMimeType("message/rfc822")) {
/* normal mail message body */
parseMessage((Part) bodyPart.getContent(), parent, buf, msgPrefixId);
// Exit point
return;
} else {
Object part = bodyPart.getContent();
boolean isTextPlain = bodyPart.isMimeType("text/plain");
if (part instanceof String) {
/* We will take the first charset encoding found for the body text of hte message.
* If there are HTML views of the data, those individual documents will be child documents with their own encodings.
*/
if (meta.charset != null && parent.getEncoding() == null) {
parent.setEncoding(meta.charset);
}
String text = (String) part;
if (!isTextPlain) {
// Decode TEXT from MIME base64 or QP encoded data.
// TODO: Is this necessary? The mime libraries seem to handle base64 unencoding automatically
// (at least for text/plain attachments). -jgibson
logger.debug("{}# Save String MIME part", msgPrefixId);
if (meta.isQP() || meta.isBase64()) {
try {
partIO = IOUtils.toInputStream(text);
byte[] textBytes = decodeMIMEText(partIO, meta.transferEncoding);
if (meta.charset != null) {
text = new String(textBytes, meta.charset);
} else {
text = new String(textBytes);
}
} catch (Exception decodeErr) {
logger.error("Decoding error with bare text in body of message");
}
} else {
logger.debug("Other encoding is unaccounted: {}", meta.transferEncoding);
}
}
if (meta.isAttachment()) {
Content child = createBaseChildContent(filename, meta);
if (child.encoding == null) {
child.encoding = "UTF-8";
}
child.content = text.getBytes(child.encoding);
copyMailAttrs(parent, child);
parent.addRawChild(child);
} else {
// Note, before trying any of these decoding trick
buf.append(TextUtils.delete_controls(text));
buf.append("\n*******************\n");
// Note, the "=XX" sequence is reserved for RFC822 encoding of special chars and non-ASCII.
// So I avoid using "=====".... as a separator.
}
// Exit point
return;
} else if (part instanceof InputStream) {
// Retrieve byte stream.
partIO = (InputStream) part;
Content child = createChildContent(filename, partIO, meta);
copyMailAttrs(parent, child);
parent.addRawChild(child);
// Exit point.
return;
} else {
/* MCU: identify unknown MIME parts */
logger.debug("Skipping this an unknown bodyPart type: " + part.getClass().getName());
//return;
}
}
if (bodyPart instanceof MimeBodyPart && !bodyPart.isMimeType("multipart/*")) {
logger.debug("{}# Saving {} ", msgPrefixId, filename);
if (meta.disposition == null || meta.isAttachment) {
partIO = ((MimeBodyPart) bodyPart).getRawInputStream();
Content child = createChildContent(filename, partIO, meta);
copyMailAttrs(parent, child);
if (meta.isHTML() && (meta.isInline() || (!meta.isAttachment()))) {
child.meta.setProperty(MAIL_KEY_PREFIX + "html-body", "true");
}
parent.addRawChild(child);
return;
}
}
} catch (MessagingException e2) {
logger.error("Extraction Failed on Messaging Exception", e2);
} finally {
if (partIO != null) {
partIO.close();
}
}
}
Aggregations