use of javax.mail.Multipart in project adempiere by adempiere.
the class RequestEMailProcessor method createRequest.
// processInBox
/**
* Create request
* @param msg message
* @return
* @return Type of Message
* @throws MessagingException
*/
private boolean createRequest(Message msg) throws MessagingException, SQLException {
// Assign from variable
Address[] from = msg.getFrom();
String fromAddress;
// Carlos Ruiz <c_ruiz@myrealbox.com>
if (from[0].toString().indexOf('<') != -1 && from[0].toString().indexOf('>') != -1) {
fromAddress = from[0].toString().substring(from[0].toString().indexOf('<') + 1, from[0].toString().indexOf('>'));
log.info("fromAddress stripped: " + fromAddress);
} else {
fromAddress = from[0].toString();
}
// Message-ID as documentNo
String[] hdrs = msg.getHeader("Message-ID");
// Review if the e-mail was already created, comparing Message-ID+From+body
int retValuedup = 0;
String sqldup = "select r_request_id from r_request " + "where ad_client_id = ? " + "and documentno = ? " + "and startdate = ?";
PreparedStatement pstmtdup = null;
pstmtdup = DB.prepareStatement(sqldup, null);
pstmtdup.setInt(1, getAD_Client_ID());
pstmtdup.setString(2, hdrs[0].substring(0, 30));
pstmtdup.setTimestamp(3, new Timestamp(msg.getSentDate().getTime()));
ResultSet rsdup = pstmtdup.executeQuery();
if (rsdup.next())
retValuedup = rsdup.getInt(1);
rsdup.close();
pstmtdup.close();
pstmtdup = null;
if (retValuedup > 0) {
log.info("request already existed for msg -> " + hdrs[0]);
return true;
}
// Analyze subject if Re: find the original request by subject + e-mail and add an action
int request_upd = 0;
String sqlupd = "SELECT r_request_id " + " FROM r_request " + " WHERE ad_client_id = ? " + " AND summary LIKE 'FROM: ' || ? || '%' " + " AND ( documentno = " + " SUBSTR " + " (?, " + " INSTR " + " (?, " + " '<' " + " ) " + " ) " + " OR ( ? LIKE 'Re: %' " + " AND summary = " + " 'FROM: ' " + " || ? " + " || CHR (10) " + " || SUBSTR (?, 5) " + " ) " + " ) ";
PreparedStatement pstmtupd = null;
pstmtupd = DB.prepareStatement(sqlupd, null);
pstmtupd.setInt(1, getAD_Client_ID());
pstmtupd.setString(2, fromAddress);
pstmtupd.setString(3, msg.getSubject());
pstmtupd.setString(4, msg.getSubject());
pstmtupd.setString(5, msg.getSubject());
pstmtupd.setString(6, fromAddress);
pstmtupd.setString(7, msg.getSubject());
ResultSet rsupd = pstmtupd.executeQuery();
if (rsupd.next())
request_upd = rsupd.getInt(1);
rsupd.close();
pstmtupd.close();
pstmtupd = null;
if (request_upd > 0) {
log.info("msg -> " + hdrs[0] + " is an answer for req " + request_upd);
return updateRequest(request_upd, msg);
}
MRequest req = new MRequest(getCtx(), 0, get_TrxName());
// Subject as summary
req.setSummary("FROM: " + fromAddress + "\n" + msg.getSubject());
// Body as result
req.setResult("FROM: " + from[0].toString() + "\n" + getMessage(msg));
// Message-ID as documentNo
if (hdrs != null)
req.setDocumentNo(hdrs[0].substring(0, 30));
// Default request type for this process
if (R_RequestType_ID > 0)
req.setR_RequestType_ID(R_RequestType_ID);
else
req.setR_RequestType_ID();
// set Default sales representative
if (SalesRep_ID > 0)
req.setSalesRep_ID(SalesRep_ID);
// set Default role
if (AD_Role_ID > 0)
req.setAD_Role_ID(AD_Role_ID);
// Look for user via e-mail
if (from != null) {
int retValueu = -1;
String sqlu = "SELECT ad_user_id " + " FROM ad_user " + " WHERE UPPER (email) = UPPER (?) " + " AND ad_client_id = ?";
PreparedStatement pstmtu = null;
pstmtu = DB.prepareStatement(sqlu, null);
pstmtu.setString(1, fromAddress);
pstmtu.setInt(2, getAD_Client_ID());
ResultSet rsu = pstmtu.executeQuery();
if (rsu.next())
retValueu = rsu.getInt(1);
rsu.close();
pstmtu.close();
pstmtu = null;
if (retValueu > 0) {
req.setAD_User_ID(retValueu);
} else {
// set default user
if (AD_User_ID > 0)
req.setAD_User_ID(AD_User_ID);
}
}
// Look BP
if (req.getAD_User_ID() > 0) {
MUser us = new MUser(getCtx(), req.getAD_User_ID(), get_TrxName());
if (us.getC_BPartner_ID() > 0)
req.setC_BPartner_ID(us.getC_BPartner_ID());
}
if (req.getC_BPartner_ID() <= 0 && C_BPartner_ID > 0) {
// set default business partner
req.setC_BPartner_ID(C_BPartner_ID);
}
// Set start date as sent date of e-mail
req.setStartDate(new Timestamp(msg.getSentDate().getTime()));
// defaults priority Medium, confidentiality partner
if (p_DefaultConfidentiality != null) {
req.setConfidentialType(p_DefaultConfidentiality);
req.setConfidentialTypeEntry(p_DefaultConfidentiality);
}
if (p_DefaultPriority != null) {
req.setPriority(p_DefaultPriority);
req.setPriorityUser(p_DefaultPriority);
}
if (req.save(get_TrxName())) {
log.info("created request " + req.getR_Request_ID() + " from msg -> " + hdrs[0]);
// get simple attachments and attach to request
if (msg.isMimeType("multipart/*")) {
try {
Multipart mp = (Multipart) msg.getContent();
for (int i = 0, n = mp.getCount(); i < n; i++) {
Part part = mp.getBodyPart(i);
String disposition = part.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
MAttachment attach = req.createAttachment();
InputStream in = part.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
//1KiB buffer
final int BUF_SIZE = 1 << 8;
byte[] buffer = new byte[BUF_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) > -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
byte[] bytes = out.toByteArray();
attach.addEntry(part.getFileName(), bytes);
attach.saveEx(get_TrxName());
}
}
} catch (IOException e) {
log.log(Level.FINE, "Error extracting attachments", e);
}
}
return true;
} else {
return false;
}
}
use of javax.mail.Multipart in project ddf by codice.
the class SmtpClientImplITCase method testSendWithAttachments.
@Test
public void testSendWithAttachments() throws IOException, MessagingException, ExecutionException, InterruptedException {
int port = findAvailablePort();
SimpleSmtpServer server = SimpleSmtpServer.start(port);
SmtpClientImpl emailService = new SmtpClientImpl();
emailService.setHostName(HOSTNAME);
emailService.setPortNumber(port);
File tmpFile = folder.newFile("email.txt");
try (OutputStream os = new FileOutputStream(tmpFile)) {
os.write(ATTACHMENT_TEXT.getBytes());
}
Session session = emailService.createSession();
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
mimeMessage.setSubject(SUBJECT);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(BODY);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(tmpFile)));
messageBodyPart.setFileName(ATTACHMENT_FILENAME);
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
emailService.send(mimeMessage).get();
server.stop();
assertThat(server.getReceivedEmailSize(), is(1));
Iterator emailIterator = server.getReceivedEmail();
SmtpMessage email = (SmtpMessage) emailIterator.next();
assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
assertThat(email.getBody(), containsString(BODY));
assertThat(email.getBody(), containsString(ATTACHMENT_TEXT));
assertThat(email.getBody(), containsString(ATTACHMENT_FILENAME));
}
use of javax.mail.Multipart in project webservices-axiom by apache.
the class TestSetOptimize method runTest.
@Override
protected void runTest() throws Throwable {
InputStream in = XOP_SPEC_SAMPLE.getInputStream();
try {
OMDocument document = OMXMLBuilderFactory.createOMBuilder(metaFactory.getOMFactory(), StAXParserConfiguration.DEFAULT, MultipartBody.builder().setInputStream(in).setContentType(XOP_SPEC_SAMPLE.getContentType()).build()).getDocument();
for (Iterator<OMSerializable> it = document.getDescendants(false); it.hasNext(); ) {
OMSerializable node = it.next();
if (node instanceof OMText) {
OMText text = (OMText) node;
if (text.isBinary()) {
text.setOptimize(optimize);
}
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
OMOutputFormat format = new OMOutputFormat();
format.setDoOptimize(true);
document.serialize(out, format);
Multipart mp = new MimeMultipart(new ByteArrayDataSource(out.toByteArray(), format.getContentType()));
assertThat(mp.getCount()).isEqualTo(optimize ? 3 : 1);
} finally {
in.close();
}
}
use of javax.mail.Multipart in project Lucee by lucee.
the class MailClient method getMultiPart.
private void getMultiPart(Query query, int row, Array attachments, Array attachmentFiles, Struct cids, Multipart multiPart, StringBuffer body) throws MessagingException, IOException {
int j = multiPart.getCount();
for (int k = 0; k < j; k++) {
BodyPart bodypart = multiPart.getBodyPart(k);
Object content;
if (bodypart.getFileName() != null) {
String filename = bodypart.getFileName();
try {
filename = Normalizer.normalize(MimeUtility.decodeText(filename), Normalizer.Form.NFC);
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
if (bodypart.getHeader("Content-ID") != null) {
String[] ids = bodypart.getHeader("Content-ID");
String cid = ids[0].substring(1, ids[0].length() - 1);
cids.setEL(KeyImpl.init(filename), cid);
}
if (filename != null && ArrayUtil.find(attachments, filename) == 0) {
attachments.appendEL(filename);
if (attachmentDirectory != null) {
Resource file = attachmentDirectory.getRealResource(filename);
int l = 1;
String s2;
for (; uniqueFilenames && file.exists(); file = attachmentDirectory.getRealResource(s2)) {
String[] as = ResourceUtil.splitFileName(filename);
s2 = as.length != 1 ? as[0] + l++ + '.' + as[1] : as[0] + l++;
}
IOUtil.copy(bodypart.getInputStream(), file, true);
attachmentFiles.appendEL(file.getAbsolutePath());
}
}
} else if (bodypart.isMimeType("text/plain")) {
content = getConent(bodypart);
query.setAtEL(TEXT_BODY, row, content);
if (body.length() == 0)
body.append(content);
} else if (bodypart.isMimeType("text/html")) {
content = getConent(bodypart);
query.setAtEL(HTML_BODY, row, content);
if (body.length() == 0)
body.append(content);
} else if ((content = bodypart.getContent()) instanceof Multipart) {
getMultiPart(query, row, attachments, attachmentFiles, cids, (Multipart) content, body);
} else if (bodypart.getHeader("Content-ID") != null) {
String[] ids = bodypart.getHeader("Content-ID");
String cid = ids[0].substring(1, ids[0].length() - 1);
String filename = "cid:" + cid;
attachments.appendEL(filename);
if (attachmentDirectory != null) {
filename = "_" + Md5.getDigestAsString(filename);
Resource file = attachmentDirectory.getRealResource(filename);
int l = 1;
String s2;
for (; uniqueFilenames && file.exists(); file = attachmentDirectory.getRealResource(s2)) {
String[] as = ResourceUtil.splitFileName(filename);
s2 = as.length != 1 ? as[0] + l++ + '.' + as[1] : as[0] + l++;
}
IOUtil.copy(bodypart.getInputStream(), file, true);
attachmentFiles.appendEL(file.getAbsolutePath());
}
cids.setEL(KeyImpl.init(filename), cid);
}
}
}
use of javax.mail.Multipart in project weicoder by wdcode.
the class EmailJava method sendEmail.
/**
* 发送Email
* @param to 发送地址
* @param subject 邮件标题
* @param msg 邮件内容
* @param attach 附件
* @param flag 是否html
*/
private void sendEmail(String[] to, String subject, String msg, String attach, boolean flag) {
try {
// 参数设置
Properties props = new Properties();
// 指定SMTP服务器
props.put("mail.smtp.host", getHost());
// 是否需要SMTP验证
props.put("mail.smtp.auth", isAuth());
// 获得Session
Session mailSession = Session.getDefaultInstance(props);
// 创建细信息类
Message message = new MimeMessage(mailSession);
// 设置邮件服务器
message.setFrom(new InternetAddress(getFrom()));
// 收件人
for (int i = 0; i < to.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
// 邮件主题
message.setSubject(subject);
// 是否支持HTML
if (flag) {
// HTML
message.setContent(msg, getCharset());
} else {
// 普通文本
message.setText(msg);
}
// 添加附件
if (!EmptyUtil.isEmpty(attach)) {
// 附件
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = null;
// 判断是本地文件还是远程
if (attach.indexOf("http") == -1) {
// 本地文件
source = new FileDataSource(attach);
} else {
// 远程文件
source = new URLDataSource(new URL(attach));
}
messageBodyPart.setDataHandler(new DataHandler(source));
// 设置描述名字等
String name = StringUtil.subStringLast(attach, StringConstants.BACKSLASH, StringConstants.POINT);
// 添加文件名和描述
messageBodyPart.setText(name);
messageBodyPart.setFileName(name);
// 附件
Multipart multipart = new MimeMultipart();
// 添加附件
multipart.addBodyPart(messageBodyPart);
// 添加到正文中
message.setContent(multipart);
}
// 保存设置
message.saveChanges();
// 发送邮件
Transport.send(message);
} catch (Exception e) {
Logs.error(e);
}
}
Aggregations