Search in sources :

Example 21 with Multipart

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";
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringUtils(org.apache.commons.lang.StringUtils) RequestParam(org.springframework.web.bind.annotation.RequestParam) URLDecoder(java.net.URLDecoder) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) CommentValidationService(org.ambraproject.wombat.service.CommentValidationService) URISyntaxException(java.net.URISyntaxException) OrcidAuthenticationTokenExpiredException(org.ambraproject.wombat.service.remote.orcid.OrcidAuthenticationTokenExpiredException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) MessagingException(javax.mail.MessagingException) FreeMarkerConfig(org.springframework.web.servlet.view.freemarker.FreeMarkerConfig) EmailValidator(org.apache.commons.validator.routines.EmailValidator) StatusLine(org.apache.http.StatusLine) EntityUtils(org.apache.http.util.EntityUtils) ArticlePointer(org.ambraproject.wombat.identity.ArticlePointer) Model(org.springframework.ui.Model) ByteArrayInputStream(java.io.ByteArrayInputStream) Gson(com.google.gson.Gson) Document(org.w3c.dom.Document) Map(java.util.Map) HoneypotService(org.ambraproject.wombat.service.HoneypotService) Splitter(com.google.common.base.Splitter) ArticleCommentFlag(org.ambraproject.wombat.model.ArticleCommentFlag) ImmutableMap(com.google.common.collect.ImmutableMap) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) FreemarkerMailService(org.ambraproject.wombat.service.FreemarkerMailService) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) UrlValidator(org.apache.commons.validator.routines.UrlValidator) Objects(java.util.Objects) DateTimeParseException(java.time.format.DateTimeParseException) Base64(java.util.Base64) List(java.util.List) CommentService(org.ambraproject.wombat.service.CommentService) LocalDate(java.time.LocalDate) ByteStreams(com.google.common.io.ByteStreams) SiteParam(org.ambraproject.wombat.config.site.SiteParam) NameValuePair(org.apache.http.NameValuePair) EmailMessage(org.ambraproject.wombat.model.EmailMessage) ServiceRequestException(org.ambraproject.wombat.service.remote.ServiceRequestException) OrcidApi(org.ambraproject.wombat.service.remote.orcid.OrcidApi) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) RequestMappingContextDictionary(org.ambraproject.wombat.config.site.RequestMappingContextDictionary) CachedRemoteService(org.ambraproject.wombat.service.remote.CachedRemoteService) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiAddress(org.ambraproject.wombat.service.remote.ApiAddress) Multipart(javax.mail.Multipart) HashMap(java.util.HashMap) Link(org.ambraproject.wombat.config.site.url.Link) Controller(org.springframework.stereotype.Controller) JsonService(org.ambraproject.wombat.service.remote.JsonService) Function(java.util.function.Function) ArticleTransformService(org.ambraproject.wombat.service.ArticleTransformService) ArrayList(java.util.ArrayList) RequestedDoiVersion(org.ambraproject.wombat.identity.RequestedDoiVersion) InternetAddress(javax.mail.internet.InternetAddress) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) Site(org.ambraproject.wombat.config.site.Site) HttpServletRequest(javax.servlet.http.HttpServletRequest) ImmutableList(com.google.common.collect.ImmutableList) Charset(java.nio.charset.Charset) SiteSet(org.ambraproject.wombat.config.site.SiteSet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CitationDownloadService(org.ambraproject.wombat.service.CitationDownloadService) ParseXmlService(org.ambraproject.wombat.service.ParseXmlService) OrcidAuthenticationTokenReusedException(org.ambraproject.wombat.service.remote.orcid.OrcidAuthenticationTokenReusedException) OutputStream(java.io.OutputStream) Charsets(com.google.common.base.Charsets) Reference(org.ambraproject.wombat.model.Reference) Logger(org.slf4j.Logger) StringWriter(java.io.StringWriter) CharMatcher(com.google.common.base.CharMatcher) HttpServletResponse(javax.servlet.http.HttpServletResponse) CorpusContentApi(org.ambraproject.wombat.service.remote.CorpusContentApi) SolrUndefinedException(org.ambraproject.wombat.service.remote.SolrUndefinedException) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) DoiToJournalResolutionService(org.ambraproject.wombat.service.DoiToJournalResolutionService) ArticleApi(org.ambraproject.wombat.service.remote.ArticleApi) HttpStatus(org.springframework.http.HttpStatus) URLEncoder(java.net.URLEncoder) EntityNotFoundException(org.ambraproject.wombat.service.EntityNotFoundException) ArticleComment(org.ambraproject.wombat.model.ArticleComment) UserApi(org.ambraproject.wombat.service.remote.UserApi) HttpResponse(org.apache.http.HttpResponse) ResponseEntity(org.springframework.http.ResponseEntity) RuntimeConfiguration(org.ambraproject.wombat.config.RuntimeConfiguration) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) InputStream(java.io.InputStream) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) EmailMessage(org.ambraproject.wombat.model.EmailMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 22 with Multipart

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;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Template(freemarker.template.Template)

Example 23 with Multipart

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();
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 24 with Multipart

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.
}
Also used : MailListener(org.xwiki.mail.MailListener) MemoryMailListener(org.xwiki.mail.internal.MemoryMailListener) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Session(javax.mail.Session) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Example 25 with Multipart

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;
}
Also used : ExtendedMimeMessage(org.xwiki.mail.ExtendedMimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Address(javax.mail.Address) MimeMultipart(javax.mail.internet.MimeMultipart) Map(java.util.Map) DocumentReference(org.xwiki.model.reference.DocumentReference)

Aggregations

Multipart (javax.mail.Multipart)140 MimeMultipart (javax.mail.internet.MimeMultipart)101 MimeBodyPart (javax.mail.internet.MimeBodyPart)87 MimeMessage (javax.mail.internet.MimeMessage)79 BodyPart (javax.mail.BodyPart)60 InternetAddress (javax.mail.internet.InternetAddress)59 MessagingException (javax.mail.MessagingException)54 Session (javax.mail.Session)42 DataHandler (javax.activation.DataHandler)40 Properties (java.util.Properties)34 IOException (java.io.IOException)33 Date (java.util.Date)29 Message (javax.mail.Message)28 FileDataSource (javax.activation.FileDataSource)26 DataSource (javax.activation.DataSource)23 InputStream (java.io.InputStream)22 File (java.io.File)21 Part (javax.mail.Part)19 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10