use of javax.mail.Multipart in project oozie by apache.
the class EmailActionExecutor method email.
public void email(String[] to, String[] cc, String[] bcc, String subject, String body, String[] attachments, String contentType, String user) throws ActionExecutorException {
// Get mailing server details.
String smtpHost = ConfigurationService.get(EMAIL_SMTP_HOST);
Integer smtpPortInt = ConfigurationService.getInt(EMAIL_SMTP_PORT);
Boolean smtpAuthBool = ConfigurationService.getBoolean(EMAIL_SMTP_AUTH);
String smtpUser = ConfigurationService.get(EMAIL_SMTP_USER);
String smtpPassword = ConfigurationService.getPassword(EMAIL_SMTP_PASS, "");
String fromAddr = ConfigurationService.get(EMAIL_SMTP_FROM);
Integer timeoutMillisInt = ConfigurationService.getInt(EMAIL_SMTP_SOCKET_TIMEOUT_MS);
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", smtpHost);
properties.setProperty("mail.smtp.port", smtpPortInt.toString());
properties.setProperty("mail.smtp.auth", smtpAuthBool.toString());
// Apply sensible timeouts, as defaults are infinite. See https://s.apache.org/javax-mail-timeouts
properties.setProperty("mail.smtp.connectiontimeout", timeoutMillisInt.toString());
properties.setProperty("mail.smtp.timeout", timeoutMillisInt.toString());
properties.setProperty("mail.smtp.writetimeout", timeoutMillisInt.toString());
Session session;
// (cause it may lead to issues when used second time).
if (!smtpAuthBool) {
session = Session.getInstance(properties);
} else {
session = Session.getInstance(properties, new JavaMailAuthenticator(smtpUser, smtpPassword));
}
Message message = new MimeMessage(session);
InternetAddress from;
List<InternetAddress> toAddrs = new ArrayList<InternetAddress>(to.length);
List<InternetAddress> ccAddrs = new ArrayList<InternetAddress>(cc.length);
List<InternetAddress> bccAddrs = new ArrayList<InternetAddress>(bcc.length);
try {
from = new InternetAddress(fromAddr);
message.setFrom(from);
} catch (AddressException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM002", "Bad from address specified in ${oozie.email.from.address}.", e);
} catch (MessagingException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM003", "Error setting a from address in the message.", e);
}
try {
// Add all <to>
for (String toStr : to) {
toAddrs.add(new InternetAddress(toStr.trim()));
}
message.addRecipients(RecipientType.TO, toAddrs.toArray(new InternetAddress[0]));
// Add all <cc>
for (String ccStr : cc) {
ccAddrs.add(new InternetAddress(ccStr.trim()));
}
message.addRecipients(RecipientType.CC, ccAddrs.toArray(new InternetAddress[0]));
// Add all <bcc>
for (String bccStr : bcc) {
bccAddrs.add(new InternetAddress(bccStr.trim()));
}
message.addRecipients(RecipientType.BCC, bccAddrs.toArray(new InternetAddress[0]));
// Set subject
message.setSubject(subject);
// when there is attachment
if (attachments != null && attachments.length > 0 && ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
Multipart multipart = new MimeMultipart();
// Set body text
MimeBodyPart bodyTextPart = new MimeBodyPart();
bodyTextPart.setText(body);
multipart.addBodyPart(bodyTextPart);
for (String attachment : attachments) {
URI attachUri = new URI(attachment);
if (attachUri.getScheme() != null && attachUri.getScheme().equals("file")) {
throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file. A local file cannot be attached:" + attachment);
}
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new URIDataSource(attachUri, user);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(new File(attachment).getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
if (attachments != null && attachments.length > 0 && !ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
body = body + EMAIL_ATTACHMENT_ERROR_MSG;
}
message.setContent(body, contentType);
}
} catch (AddressException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM004", "Bad address format in <to> or <cc> or <bcc>.", e);
} catch (MessagingException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM005", "An error occurred while adding recipients.", e);
} catch (URISyntaxException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
} catch (HadoopAccessorException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
}
try {
// Send over SMTP Transport
// (Session+Message has adequate details.)
Transport.send(message);
} catch (NoSuchProviderException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM006", "Could not find an SMTP transport provider to email.", e);
} catch (MessagingException e) {
throw new ActionExecutorException(ErrorType.ERROR, "EM007", "Encountered an error while sending the email message over SMTP.", e);
}
LOG.info("Email sent to [{0}]", to);
}
use of javax.mail.Multipart in project oozie by apache.
the class TestEmailActionExecutor method testHDFSFileAttachment.
public void testHDFSFileAttachment() throws Exception {
String file1 = "file1";
Path path1 = new Path(getFsTestCaseDir(), file1);
String content1 = "this is attachment content in file1";
String file2 = "file2";
Path path2 = new Path(getFsTestCaseDir(), file2);
String content2 = "this is attachment content in file2";
FileSystem fs = getFileSystem();
Writer writer = new OutputStreamWriter(fs.create(path1, true));
writer.write(content1);
writer.close();
writer = new OutputStreamWriter(fs.create(path2, true));
writer.write(content2);
writer.close();
StringBuilder tag = new StringBuilder();
tag.append(path1.toString()).append(",").append(path2.toString());
assertAttachment(tag.toString(), 2, content1, content2);
// test case when email attachment support set to false
ConfigurationService.setBoolean(EmailActionExecutor.EMAIL_ATTACHMENT_ENABLED, false);
sendAndReceiveEmail(tag.toString());
MimeMessage retMeg = server.getReceivedMessages()[1];
String msgBody = GreenMailUtil.getBody(retMeg);
assertEquals(msgBody.indexOf("This is a test mail"), 0);
assertNotSame(msgBody.indexOf(EmailActionExecutor.EMAIL_ATTACHMENT_ERROR_MSG), -1);
// email content is not multi-part since not attaching files
assertFalse(retMeg.getContent() instanceof Multipart);
assertTrue(retMeg.getContentType().contains("text/plain"));
}
use of javax.mail.Multipart in project ecs-dashboard by carone1.
the class KibanaEmailer method sendFileEmail.
/*
* Utility method that grabs png files and send them
* to a list of email addresses
*/
private static void sendFileEmail(String security) {
final String username = smtpUsername;
final String password = smtpPassword;
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", smtpHost);
if (security.equals(SMTP_SECURITY_TLS)) {
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.port", smtpPort);
} else if (security.equals(SMTP_SECURITY_SSL)) {
properties.put("mail.smtp.socketFactory.port", smtpPort);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", smtpPort);
}
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(sourceAddress));
// Set To: header field of the header.
for (String destinationAddress : destinationAddressList) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
}
// Set Subject: header field
message.setSubject(mailTitle);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
StringBuffer bodyBuffer = new StringBuffer(mailBody);
if (!kibanaUrls.isEmpty()) {
bodyBuffer.append("\n\n");
}
// Add urls info to e-mail
for (Map<String, String> kibanaUrl : kibanaUrls) {
// Add urls to e-mail
String urlName = kibanaUrl.get(NAME_KEY);
String reportUrl = kibanaUrl.get(URL_KEY);
if (urlName != null && reportUrl != null) {
bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
}
}
// Fill the message
messageBodyPart.setText(bodyBuffer.toString());
// Create a multipart message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachments
for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
messageBodyPart = new MimeBodyPart();
String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
DataSource source = new FileDataSource(absoluteFilename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
logger.info("Sent mail message successfully");
} catch (MessagingException mex) {
throw new RuntimeException(mex);
}
}
use of javax.mail.Multipart in project javautils by jiadongpo.
the class MyMailTest method main.
public static void main(String[] args) throws Exception {
// 会话===========================
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
// 需要验证
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
// msg 设置=======================
MimeMessage mimeMsg = new MimeMessage(session);
// 设置标题
mimeMsg.setSubject("标题test");
// 设置内容----begin
Multipart mp = new MimeMultipart();
// 添加文本
BodyPart bp1 = new MimeBodyPart();
bp1.setContent("文本内容", "text/html;charset=GB2312");
mp.addBodyPart(bp1);
// 添加附件
BodyPart bp2 = new MimeBodyPart();
FileDataSource fileds = new FileDataSource("c:\\boot.ini");
bp2.setDataHandler(new DataHandler(fileds));
bp2.setFileName(fileds.getName());
mp.addBodyPart(bp2);
mimeMsg.setContent(mp);
// 设置内容----end
mimeMsg.setFrom(new InternetAddress("xiangzhengyan@163.com"));
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xiangyh@asiacom-online.com"));
mimeMsg.saveChanges();
// 传输==================================
Transport transport = session.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"), "xiangzhengyan", "pass");
transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
transport.close();
}
use of javax.mail.Multipart in project mailim by zengsn.
the class EmaiRecever method getPicMultipart.
/**
* 解析图片内容
* @param part
* @throws Exception
*/
private static void getPicMultipart(Part part) throws Exception {
if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int count = multipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.isMimeType("image/*")) {
InputStream is = bodyPart.getInputStream();
FileOutputStream fos = new FileOutputStream("路径+文件名");
int len = 0;
byte[] bys = new byte[1024];
while ((len = is.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.close();
}
}
}
}
Aggregations