use of javax.mail.internet.MimeBodyPart in project webservices-axiom by apache.
the class TestCreateSOAPModelBuilderMTOMContentTypeMismatch method runTest.
@Override
protected void runTest() throws Throwable {
final SOAPSample sample = SOAPSampleSet.NO_HEADER.getMessage(spec);
// Generate an MTOM message with the wrong content type
MimeMessage message = new MimeMessage((Session) null);
MimeMultipart mp = new MimeMultipart("related");
MimeBodyPart bp = new MimeBodyPart();
String contentID = "<" + UIDGenerator.generateContentId() + ">";
bp.setDataHandler(new DataHandler(new DataSource() {
@Override
public String getContentType() {
return "application/xop+xml; charset=\"" + sample.getEncoding() + "\"; type=\"" + spec.getAltSpec().getContentType() + "\"";
}
@Override
public InputStream getInputStream() throws IOException {
return sample.getInputStream();
}
@Override
public String getName() {
return null;
}
@Override
public OutputStream getOutputStream() {
throw new UnsupportedOperationException();
}
}));
bp.addHeader("Content-Transfer-Encoding", "binary");
bp.addHeader("Content-ID", contentID);
mp.addBodyPart(bp);
message.setContent(mp);
message.saveChanges();
ContentType contentType = new ContentType(message.getContentType()).toBuilder().setParameter("type", "application/xop+xml").setParameter("start", contentID).setParameter("start-info", spec.getAltSpec().getContentType()).build();
MemoryBlob blob = Blobs.createMemoryBlob();
OutputStream out = blob.getOutputStream();
mp.writeTo(out);
out.close();
// Now attempt to create an Axiom builder
try {
OMXMLBuilderFactory.createSOAPModelBuilder(metaFactory, MultipartBody.builder().setInputStream(blob.getInputStream()).setContentType(contentType).build());
fail("Expected SOAPProcessingException");
} catch (SOAPProcessingException ex) {
// Expected
}
}
use of javax.mail.internet.MimeBodyPart in project webservices-axiom by apache.
the class AbstractMultipartWriterTest method test.
private void test(String contentTransferEncoding) throws Exception {
Random random = new Random();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MultipartWriter mpw = factory.createMultipartWriter(baos, UIDGenerator.generateMimeBoundary());
byte[] content = new byte[8192];
random.nextBytes(content);
OutputStream partOutputStream = mpw.writePart("application/octet-stream", contentTransferEncoding, UIDGenerator.generateContentId());
partOutputStream.write(content);
partOutputStream.close();
mpw.complete();
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray()));
assertEquals(1, mp.getCount());
MimeBodyPart bp = (MimeBodyPart) mp.getBodyPart(0);
assertEquals(contentTransferEncoding, bp.getHeader("Content-Transfer-Encoding")[0]);
baos.reset();
bp.getDataHandler().writeTo(baos);
assertTrue(Arrays.equals(content, baos.toByteArray()));
}
use of javax.mail.internet.MimeBodyPart in project Gargoyle by callakrsos.
the class EmailAttachmentSender method sendEmailWithAttachments.
public static void sendEmailWithAttachments(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
use of javax.mail.internet.MimeBodyPart in project ddf by codice.
the class SmtpClientImplITCase method testSend.
@Test
public void testSend() throws IOException, MessagingException, ExecutionException, InterruptedException {
int port = findAvailablePort();
SimpleSmtpServer server = SimpleSmtpServer.start(port);
SmtpClientImpl emailService = new SmtpClientImpl();
emailService.setHostName(HOSTNAME);
emailService.setPortNumber(port);
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);
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));
}
use of javax.mail.internet.MimeBodyPart in project gitblit by gitblit.
the class MailService method createMessage.
/**
* Create a message.
*
* @param mailing
* @return a message
*/
public Message createMessage(Mailing mailing) {
if (mailing.subject == null) {
mailing.subject = "";
}
if (mailing.content == null) {
mailing.content = "";
}
Message message = new MailMessageImpl(session, mailing.id);
try {
String fromAddress = settings.getString(Keys.mail.fromAddress, null);
if (StringUtils.isEmpty(fromAddress)) {
fromAddress = "gitblit@gitblit.com";
}
InternetAddress from = new InternetAddress(fromAddress, mailing.from == null ? "Gitblit" : mailing.from);
message.setFrom(from);
Pattern validEmail = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
// validate & add TO recipients
List<InternetAddress> to = new ArrayList<InternetAddress>();
for (String address : mailing.toAddresses) {
if (StringUtils.isEmpty(address)) {
continue;
}
if (validEmail.matcher(address).find()) {
try {
to.add(new InternetAddress(address));
} catch (Throwable t) {
}
}
}
// validate & add CC recipients
List<InternetAddress> cc = new ArrayList<InternetAddress>();
for (String address : mailing.ccAddresses) {
if (StringUtils.isEmpty(address)) {
continue;
}
if (validEmail.matcher(address).find()) {
try {
cc.add(new InternetAddress(address));
} catch (Throwable t) {
}
}
}
if (settings.getBoolean(Keys.web.showEmailAddresses, true)) {
// full disclosure of recipients
if (to.size() > 0) {
message.setRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));
}
if (cc.size() > 0) {
message.setRecipients(Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()]));
}
} else {
// everyone is bcc'd
List<InternetAddress> bcc = new ArrayList<InternetAddress>();
bcc.addAll(to);
bcc.addAll(cc);
message.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
}
message.setSentDate(new Date());
// UTF-8 encode
message.setSubject(MimeUtility.encodeText(mailing.subject, "utf-8", "B"));
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(mailing.content, "utf-8");
if (Mailing.Type.html == mailing.type) {
messagePart.setHeader("Content-Type", "text/html; charset=\"utf-8\"");
} else {
messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
}
MimeMultipart multiPart = new MimeMultipart();
multiPart.addBodyPart(messagePart);
// handle attachments
if (mailing.hasAttachments()) {
for (File file : mailing.attachments) {
if (file.exists()) {
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
multiPart.addBodyPart(filePart);
}
}
}
message.setContent(multiPart);
} catch (Exception e) {
logger.error("Failed to properly create message", e);
}
return message;
}
Aggregations