use of javax.mail.Multipart in project wombat by PLOS.
the class ArticleController method emailArticle.
/**
* @param model data passed in from the view
* @param site current site
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "emailPost", value = "/article/email", method = RequestMethod.POST)
public String emailArticle(HttpServletRequest request, HttpServletResponse response, Model model, @SiteParam Site site, RequestedDoiVersion articleId, @RequestParam("articleUri") String articleUri, @RequestParam("emailToAddresses") String emailToAddresses, @RequestParam("emailFrom") String emailFrom, @RequestParam("senderName") String senderName, @RequestParam("note") String note, @RequestParam(value = "authorPhone", required = false) String authorPhone, @RequestParam(value = "authorAffiliation", required = false) String authorAffiliation) throws IOException, MessagingException {
requireNonemptyParameter(articleUri);
model.addAttribute("emailToAddresses", emailToAddresses);
model.addAttribute("emailFrom", emailFrom);
model.addAttribute("senderName", senderName);
model.addAttribute("note", note);
model.addAttribute("articleUri", articleUri);
List<InternetAddress> toAddresses = Splitter.on(CharMatcher.anyOf("\n\r")).omitEmptyStrings().splitToList(emailToAddresses).stream().map(email -> EmailMessage.createAddress(null, /*name*/
email)).collect(Collectors.toList());
Set<String> errors = validateEmailArticleInput(toAddresses, emailFrom, senderName);
if (applyValidation(response, model, errors)) {
return renderEmailThisArticle(request, model, site, articleId);
}
Map<String, ?> articleMetadata = articleMetadataFactory.get(site, articleId).validateVisibility("emailPost").getIngestionMetadata();
String title = articleMetadata.get("title").toString();
model.addAttribute("article", articleMetadata);
model.addAttribute("journalName", site.getJournalName());
if (honeypotService.checkHoneypot(request, authorPhone, authorAffiliation)) {
response.setStatus(HttpStatus.CREATED.value());
return site + "/ftl/article/emailSuccess";
}
Multipart content = freemarkerMailService.createContent(site, "emailThisArticle", model);
EmailMessage message = EmailMessage.builder().addToEmailAddresses(toAddresses).setSenderAddress(EmailMessage.createAddress(senderName, emailFrom)).setSubject("An Article from " + site.getJournalName() + ": " + title).setContent(content).setEncoding(freeMarkerConfig.getConfiguration().getDefaultEncoding()).build();
message.send(javaMailSender);
response.setStatus(HttpStatus.CREATED.value());
return site + "/ftl/article/emailSuccess";
}
use of javax.mail.Multipart in project wombat by PLOS.
the class FreemarkerMailServiceImpl method createContent.
@Override
public Multipart createContent(Site site, String templateFilename, Model context) throws IOException, MessagingException {
Template textTemplate = getEmailTemplate(site, "txt", templateFilename);
Template htmlTemplate = getEmailTemplate(site, "html", templateFilename);
// Create a "text" Multipart message
Multipart mp = createPartForMultipart(textTemplate, context, "alternative", ContentType.TEXT_PLAIN);
// Create a "HTML" Multipart message
Multipart htmlContent = createPartForMultipart(htmlTemplate, context, "related", ContentType.TEXT_HTML);
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent);
mp.addBodyPart(htmlPart);
return mp;
}
use of javax.mail.Multipart in project Java-Tutorial by gpcodervn.
the class SendAttachment method main.
public static void main(String[] args) {
// 1) get the session object
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", MailConfig.HOST_NAME);
props.put("mail.smtp.socketFactory.port", MailConfig.SSL_PORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", MailConfig.SSL_PORT);
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MailConfig.APP_EMAIL, MailConfig.APP_PASSWORD);
}
});
// 2) compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(MailConfig.APP_EMAIL));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(MailConfig.RECEIVE_EMAIL));
message.setSubject("Sending email with attachment");
// 3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Welcome to gpcoder.com");
// 4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "data/myfile.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// 5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
// 6) set the multiplart object to the message object
message.setContent(multipart);
// 7) send message
Transport.send(message);
System.out.println("Message sent successfully");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
use of javax.mail.Multipart in project xwiki-platform by xwiki.
the class JavaIntegrationTest method sendTextMail.
@Test
public void sendTextMail() throws Exception {
// Step 1: Create a JavaMail Session
Session session = Session.getInstance(this.configuration.getAllProperties());
// Step 2: Create the Message to send
MimeMessage message = new MimeMessage(session);
message.setSubject("subject");
message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));
// Step 3: Add the Message Body
Multipart multipart = new MimeMultipart("mixed");
// Add text in the body
multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain")));
message.setContent(multipart);
// We also test using some default BCC addresses from configuration in this test
this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));
// Ensure we do not reuse the same message identifier for multiple similar messages in this test
MimeMessage message2 = new MimeMessage(message);
message2.saveChanges();
MimeMessage message3 = new MimeMessage(message);
message3.saveChanges();
// Step 4: Send the mail and wait for it to be sent
// Send 3 mails (3 times the same mail) to verify we can send several emails at once.
MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);
// Note: we don't test status reporting from the listener since this is already tested in the
// ScriptingIntegrationTest test class.
// Verify that the mails have been received (wait maximum 30 seconds).
this.mail.waitForIncomingEmail(30000L, 3);
MimeMessage[] messages = this.mail.getReceivedMessages();
// Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
assertEquals(9, messages.length);
// Assert the email parts that are the same for all mails
assertEquals("subject", messages[0].getHeader("Subject", null));
assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
assertEquals("some text here", textBodyPart.getContent());
assertEquals("john@doe.com", messages[0].getHeader("To", null));
// Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
// messages ;) But we checked that we received 9 emails above so that's good enough.
}
use of javax.mail.Multipart in project xwiki-platform by xwiki.
the class AbstractTemplateMimeMessageFactory method createMessage.
@Override
public MimeMessage createMessage(Object templateReferenceObject, Map<String, Object> parameters) throws MessagingException {
DocumentReference templateReference = getTypedSource(templateReferenceObject, DocumentReference.class);
// Note: We don't create a Session here ATM since it's not required. The returned MimeMessage will be
// given a valid Session when it's deserialized from the mail content store for sending.
ExtendedMimeMessage message = new ExtendedMimeMessage();
// Handle optional "from" address.
Address from = this.converterManager.convert(Address.class, parameters.get("from"));
if (from != null) {
message.setFrom(from);
}
// Handle optional "to", "cc" and "bcc" addresses.
setRecipient(message, Message.RecipientType.TO, parameters.get("to"));
setRecipient(message, Message.RecipientType.CC, parameters.get("cc"));
setRecipient(message, Message.RecipientType.BCC, parameters.get("bcc"));
// Handle optional "type" parameter to set the mail type
// Set the Message type if passed in parameters
String type = (String) parameters.get("type");
if (type != null) {
message.setType(type);
}
// Handle the subject. Get it from the template
Map<String, Object> velocityVariables = (Map<String, Object>) parameters.get("velocityVariables");
Object localeValue = parameters.get("language");
String subject = getTemplateManager().evaluate(templateReference, "subject", velocityVariables, localeValue);
message.setSubject(subject);
// Add a default body part taken from the template.
Multipart multipart = new MimeMultipart("mixed");
multipart.addBodyPart(getMimeBodyPartFactory().create(templateReference, parameters));
message.setContent(multipart);
return message;
}
Aggregations