working on it ...

Filters

Explore Public Snippets

Sort by

Found 716 snippets matching: attachments

    public by sherazam modified Dec 23, 2015  2904  1  6  0

    How to Manage Attachments in Existing & New Email Messages inside Android Apps

    // Enter here the actual content of the snippet.            //Adding Attachments to a New Email Message
    
    public static void AddAttachmentsToMessage()
    {
    //Base folder
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";
    
    //Create an instance of MailMessage class
    MailMessage message = new MailMessage();
    
    //From
    message.setFrom(new MailAddress("sender@sender.com"));
    
    //To whom
    message.getTo().add(new MailAddress("receiver@gmail.com"));
    
    //Adding 1st attachment
    //Create an instance of Attachment class
    Attachment attachment;
    
    //Load an attachment
    attachment = new Attachment(strBaseFolder + "1.txt");
    
    //Add attachment in instance of MailMessage class
    message.getAttachments().add(attachment);
    
    //Add 2nd Attachment
    message.getAttachments().add(new Attachment(strBaseFolder + "1.jpg"));
    
    //Add 3rd Attachment
    message.getAttachments().add(new Attachment(strBaseFolder + "1.doc"));
    
    //Add 4th Attachment
    message.getAttachments().add(new Attachment(strBaseFolder + "1.rar"));
    
    //Add 5th Attachment
    message.getAttachments().add(new Attachment(strBaseFolder + "1.pdf"));
    
    //Save message to disc
    message.save(strBaseFolder + "output.msg",MessageFormat.getMsg());
    }
    
    //Extracting Attachments from an Existing Email Message
    
    public static void ExtractAttachmentsFromMessage()
    {
        // Base folder for reading and writing files
       String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
       strBaseFolder = strBaseFolder + "/";
    
        //Initialize and Load an existing EML file by specifying the MessageFormat
        MailMessage msg = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());
    
        //Initialize AttachmentCollection object with MailMessage Attachments
        AttachmentCollection attachments =  msg.getAttachments();
    
        //Iterate over the AttachmentCollection
        for(int index = 0; index < attachments.size(); index++)
        {
            //Initialize Attachment object and Get the indexed Attachment reference
            Attachment attachment = (Attachment) attachments.get(index);
            //Display Attachment Name
            System.out.println(attachment.getName());
            //Save Attachment to disk
            attachment.save(strBaseFolder + "attachment_"+ attachment.getName());
        }
    }
    
    //Adding or Removing Attachments from an Existing Email Message
    
    public static void RemoveAttachmentsFromMessage()
    {
        // Base folder for reading and writing files
        String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
        strBaseFolder = strBaseFolder + "/";
    
        //Initialize and Load an existing EML file by specifying the MessageFormat
        MailMessage message = MailMessage.load(strBaseFolder + "AnEmail.eml", MessageFormat.getEml());
    
        //Initialize AttachmentCollection object with MailMessage Attachments
        AttachmentCollection attachments =  message.getAttachments();
        System.out.println("Attachment Count: " + attachments.size());
    
        //Check if AttachmentCollection size is greater than 0
        if(attachments.size() > 0)
        {
            //Remove Attachment from index location 0
            attachments.remove(0);
            System.out.println("Attachment Count: " + attachments.size());
        }
    
        //Add a PDF file as Attachment to the message
        message.addAttachment(new Attachment(strBaseFolder + "Blank.PDF"));
        System.out.println("Attachment Count: " + attachments.size());
    
        //Save the Email message to disk by specifying the EML MailMessageSaveType
        message.save(strBaseFolder + "message.eml", MailMessageSaveType.getEmlFormat());
    }
    
    

    public by johansonkatherine modified May 22, 2014  4415  1  6  2

    Load Existing Email Message and Modify its Contents inside Android Apps

    This technical tip shows how to load any existing email message and modify its contents before saving it back to disk using Aspose.Email for Android API. To do this successfully, specify the MessageFormat when loading the email message from disk. In addition, it is important to specify the correct MailMessageSaveType when saving the message back to
    public static void UpdateAndSaveEmail()
    {
        // Base folder for reading and writing files
    String  strBaseFolder  = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";
    
        //Initialize and load an existing MSG file by specifying the MessageFormat
    MailMessage email = MailMessage.load(strBaseFolder + "anEmail.msg", MessageFormat.getMsg());
    
        //Initialize a String variable to get the Email Subject
        String subject = email.getSubject();
        //Append some more information to Subject
    subject = subject + " This text is added to the existing subject";
        //Set the Email Subject
    email.setSubject(subject);
    
        //Initialize a String variable to get the Email's HTML Body
        String body = email.getHtmlBody();
        //Apppend some more information to the Body variable
    body = body + "<br> This text is added to the existing body";
        //Set the Email Body
    email.setHtmlBody(body);
    
        //Initialize MailAddressCollection object
    MailAddressCollection contacts = new MailAddressCollection();
    
        //Retrieve Email's TO list
    contacts = email.getTo();
        //Check if TO list has some values
    if (contacts.size() > 0)
        {
            //Remove the first email address
    contacts.remove(0);
            //Add another email address to collection
    contacts.add("to1@domain.com");
        }
        //Set the collection as Email's TO list
    email.setTo(contacts);
    
        //Initialize MailAddressCollection
    contacts = new MailAddressCollection();
    
        //Retrieve Email's CC list
    contacts = email.getCC();
        //Add another email address to collection
    contacts.add("cc2@domain.com");
        //Set the collection as Email's CC list
    email.setCC(contacts);
    
        //Save the Email message to disk by specifying the MessageFormat
    email.save(strBaseFolder + "message.msg", MailMessageSaveType.getOutlookMessageFormat());
    

    public by JPM modified Nov 14, 2017  75  0  3  0

    draw Node Attachments

    public void drawNodeAttachments(long tabNodeId) throws Exception {
    		getDocumentBean().getRequestNodeAttachments().clear();
    		getDocumentBean().getRequestNodeAttachmentsRemove().clear();
    		sarf2DTO.setNotes(requestNotesCycleService.findLastNote(AccountingConstant.SARF2_TABLE_ID,
    				sarf2DTO.getId(),tabNodeId));
    		List<RequestNodeAttachment> requestNodeAttachmentList = requestNodeAttachmentService.getNodeAttachments(AccountingConstant.SARF2_TABLE_ID
    				,tabNodeId,sarf2DTO.getId());
    		if(requestNodeAttachmentList != null && !requestNodeAttachmentList.isEmpty())
    			getDocumentBean().getRequestNodeAttachments().addAll(requestNodeAttachmentList);
    	}

    public by sherazam modified Jan 27, 2016  2502  3  6  0

    How to Extract Text from PDF Documents Based on Columns inside .NET Apps

    // Enter here the actual content of the snippet.            //The following code snippet shows the steps to reduce text size and then try extracting text from PDF document.
    
    //[C# Code Sample]
     
    
    string path = "D:\\Temp\\";
    InitLicense();
    Document pdfDocument = new Document(path + "net_New-age NED's.pdf");
    
    TextFragmentAbsorber tfa = new TextFragmentAbsorber();
    pdfDocument.Pages.Accept(tfa);
    TextFragmentCollection tfc = tfa.TextFragments;
    foreach (TextFragment tf in tfc)
    {
        //need to reduce font size at least for 70%
        tf.TextState.FontSize = tf.TextState.FontSize * 0.7f;
    }
    Stream st = new MemoryStream();
    pdfDocument.Save(st);
    pdfDocument = new Document(st);
    
    TextAbsorber textAbsorber = new TextAbsorber();
    pdfDocument.Pages.Accept(textAbsorber);
    String extractedText = textAbsorber.Text;
    textAbsorber.Visit(pdfDocument);
    
    System.IO.File.WriteAllText(path + "Extracted.txt", extractedText);
    
    // [VB.NET Code Sample]
     
    
    Dim path As String = "D:\\Temp\\"
    ' instantiate Document object 
    Dim pdfDocument As Document = New Document(path + "net_New-age NED's.pdf")
    
    Dim tfa As Aspose.Pdf.Text.TextFragmentAbsorber = New Aspose.Pdf.Text.TextFragmentAbsorber()
    pdfDocument.Pages.Accept(tfa)
    Dim tfc As Aspose.Pdf.Text.TextFragmentCollection = tfa.TextFragments
    For Each tf As Aspose.Pdf.Text.TextFragment In tfc
    
        ' need to reduce font size at least for 70%
        tf.TextState.FontSize = tf.TextState.FontSize * 0.7F
    Next
    ' create temporary stream object
    Dim st As Stream = New MemoryStream()
    ' save PDF file with reduced font size
    pdfDocument.Save(st)
    ' Instantiate Document object with stream instance
    pdfDocument = New Document(st)
    
    Dim textAbsorber As Aspose.Pdf.Text.TextAbsorber = New Aspose.Pdf.Text.TextAbsorber()
    pdfDocument.Pages.Accept(textAbsorber)
    Dim extractedText As String = textAbsorber.Text
    textAbsorber.Visit(pdfDocument)
    
    System.IO.File.WriteAllText(path + "Extracted.txt", extractedText)
     
    //Second approach - Using ScaleFactor
    
    //[C# Code Sample]
     
    
    Document pdfDocument = new Document(inputFile);
    
    TextAbsorber textAbsorber = new TextAbsorber();
    textAbsorber.ExtractionOptions = new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
    //Setting scale factor to 0.5 is enough to split columns in the majority of documents
    //Setting of zero allows to algorithm choose scale factor automatically
    textAbsorber.ExtractionOptions.ScaleFactor = 0.5; /* 0; */
    pdfDocument.Pages.Accept(textAbsorber);
    String extractedText = textAbsorber.Text;
    
    System.IO.File.WriteAllText(outFile, extractedText);
     
    // [VB.NET Code Sample]
     
    
    Dim pdfDocument As Document = New Document(inputFile)
    
    Dim textAbsorber As Aspose.Pdf.Text.TextAbsorber = New Aspose.Pdf.Text.TextAbsorber()
    textAbsorber.ExtractionOptions = New TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure)
    'Setting scale factor to 0.5 is enough to split columns in the majority of documents
    'Setting of zero allows to algorithm choose scale factor automatically
    textAbsorber.ExtractionOptions.ScaleFactor = 0.5 ' 0;
    pdfDocument.Pages.Accept(textAbsorber)
    Dim extractedText As String = textAbsorber.Text
    
    System.IO.File.WriteAllText(outFile, extractedText)
    

    public by msdn modified Jan 12, 2015  1379  1  7  0

    CreateAttachmentsItem: Create a new AttachmentsItem object.

    Create a new AttachmentsItem object. Initial value of EntitySet. Initial value of ItemId. Initial value of Name.
    /// <summary>
    /// Create a new AttachmentsItem object.
    /// </summary>
    /// <param name="entitySet">Initial value of EntitySet.</param>
    /// <param name="itemId">Initial value of ItemId.</param>
    /// <param name="name">Initial value of Name.</param>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
    public static AttachmentsItem CreateAttachmentsItem(string entitySet, int itemId, string name)
    {
        AttachmentsItem attachmentsItem = new AttachmentsItem();
        attachmentsItem.EntitySet = entitySet;
        attachmentsItem.ItemId = itemId;
        attachmentsItem.Name = name;
        return attachmentsItem;
    }

    external by dfinke modified Oct 24, 2014  401  0  3  0

    Uses COM to Look at yesterdays messages for a particular outlook account. Reporting Date, Subject and # Of Attachments

    Uses COM to Look at yesterdays messages for a particular outlook account. Reporting Date, Subject and # Of Attachments: GetOutlookMessages.ps1
    $email      = 'finked@hotmail.com'
    $targetDate = (Get-Date).AddDays(-1).ToString("d") # yesterday
    
    if(Get-Process outlook -ErrorAction Ignore) {
        return "Please stop Outlook and re-run"    
    }
    
    Write-Progress -Activity "Outlook" -Status "Connecting" 
    if($script:outlook -eq $null) { $script:outlook = new-object -com outlook.application }
    
    $olFolderInbox = 6 
    
    Write-Progress -Activity "Outlook" -Status "Connecting to target mailbox" 
    $ns       = $outlook.GetNameSpace("MAPI")
    $account  = $ns.Folders | Where-Object {$PSItem.FolderPath -match $email}
    $inbox    = $account.Folders|?{$_.name -eq 'inbox'}
    
    
    Write-Progress -Activity "Outlook" -Status "Getting messages for $($targetDate)" 
    
    ($inbox.items.Restrict("[LastModificationTime] > '$($targetDate)'")) |
        sort LastModificationTime -Descending|
        ForEach {
            [PSCustomObject][Ordered]@{
                Date = $_.LastModificationTime 
                Subject = $_.Subject
                TotalAttachments=$_.Attachments.count
            }
        } | Out-GridView
    
    $script:outlook.quit()
    [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$script:outlook) 
    $script:outlook=$null
    
    ps outlook | kill
    
    

    external by bleroy modified Apr 1, 2015  400  0  4  0

    CodePlex Issue #16335 Plain Text Attachments

    CodePlex Issue #16335 Plain Text Attachments: 16335.patch
    diff --git a/src/Orchard.Web/Modules/Orchard.Blogs/Controllers/BlogPostAdminController.cs b/src/Orchard.Web/Modules/Orchard.Blogs/Controllers/BlogPostAdminController.cs
    --- a/src/Orchard.Web/Modules/Orchard.Blogs/Controllers/BlogPostAdminController.cs
    +++ b/src/Orchard.Web/Modules/Orchard.Blogs/Controllers/BlogPostAdminController.cs
    @@ -1,3 +1,4 @@
    +using System;
     using System.Web.Mvc;
     using Orchard.Blogs.Drivers;
     using Orchard.Blogs.Extensions;
    @@ -8,14 +9,18 @@
     using Orchard.Localization;
     using Orchard.Mvc.AntiForgery;
     using Orchard.Mvc.Results;
    +using Orchard.Mvc.ViewModels;
     using Orchard.UI.Admin;
     using Orchard.UI.Notify;
    +using Orchard.Extensions;
     
     namespace Orchard.Blogs.Controllers {
         [ValidateInput(false), Admin]
         public class BlogPostAdminController : Controller, IUpdateModel {
             private readonly IBlogService _blogService;
             private readonly IBlogPostService _blogPostService;
    +        private const string PublishLater = "PublishLater";
    +        private const string PublishNow = "PublishNow";
     
             public BlogPostAdminController(IOrchardServices services, IBlogService blogService, IBlogPostService blogPostService) {
                 Services = services;
    @@ -55,6 +60,8 @@
     
                 model.BlogPost = Services.ContentManager.UpdateEditorModel(blogPost, this);
     
    +            Validate(model.BlogPost);
    +
                 if (!ModelState.IsValid) {
                     Services.TransactionManager.Cancel();
                     return View(model);
    @@ -64,12 +71,13 @@
                 Services.ContentManager.UpdateEditorModel(blogPost, this);
     
                 // Execute publish command
    +            
                 switch (Request.Form["Command"]) {
    -                case "PublishNow":
    +                case PublishNow:
                         _blogPostService.Publish(model.BlogPost.Item);
                         Services.Notifier.Information(T("Blog post has been published"));
                         break;
    -                case "PublishLater":
    +                case PublishLater:
                         _blogPostService.Publish(model.BlogPost.Item, model.BlogPost.Item.ScheduledPublishUtc.Value);
                         Services.Notifier.Information(T("Blog post has been scheduled for publishing"));
                         break;
    @@ -81,6 +89,27 @@
                 return Redirect(Url.BlogPostEdit(model.BlogPost.Item));
             }
     
    +        private void Validate(ContentItemViewModel<BlogPost> model) {
    +            
    +            if (Request.Form["Command"] == PublishLater) {
    +
    +                if (model.Item.ScheduledPublishUtc.HasValue && model.Item.ScheduledPublishUtc.Value < DateTime.Now) {
    +                    ModelState.AddModelError("ScheduledPublishUtcDate",
    +                                             T("You cannot schedule a publishing date in the past").ToString());
    +                }
    +
    +                if (model.Item.ScheduledPublishUtcDate == "Date" ||
    +                    model.Item.ScheduledPublishUtcDate.IsNullOrEmptyTrimmed()) {
    +                        ModelState.AddModelError("ScheduledPublishUtcDate", T("You must select a publishing date").ToString());
    +                }
    +
    +                if (model.Item.ScheduledPublishUtcTime == "Time" ||
    +                    model.Item.ScheduledPublishUtcTime.IsNullOrEmptyTrimmed()) {
    +                        ModelState.AddModelError("ScheduledPublishUtcTime", T("You must select a publishing time").ToString());
    +                }
    +            }
    +        }
    +
             public ActionResult Edit(string blogSlug, int postId) {
                 if (!Services.Authorizer.Authorize(Permissions.EditBlogPost, T("Couldn't edit blog post")))
                     return new HttpUnauthorizedResult();
    @@ -121,6 +150,8 @@
     
                 TryUpdateModel(model);
     
    +            Validate(model.BlogPost);
    +
                 if (!ModelState.IsValid) {
                     Services.TransactionManager.Cancel();
                     return View(model);
    diff --git a/src/Orchard.Web/Modules/Orchard.Blogs/Views/EditorTemplates/Parts/Blogs.BlogPost.Publish.ascx b/src/Orchard.Web/Modules/Orchard.Blogs/Views/EditorTemplates/Parts/Blogs.BlogPost.Publish.ascx
    --- a/src/Orchard.Web/Modules/Orchard.Blogs/Views/EditorTemplates/Parts/Blogs.BlogPost.Publish.ascx
    +++ b/src/Orchard.Web/Modules/Orchard.Blogs/Views/EditorTemplates/Parts/Blogs.BlogPost.Publish.ascx
    @@ -19,14 +19,17 @@
             <label class="forcheckbox" for="Command_PublishNow"><%=_Encoded("Publish Now")%></label>
         </div>
         <div>
    +        
             <%=Html.RadioButton("Command", "PublishLater", Model.ScheduledPublishUtc != null, new { id = "Command_PublishLater" }) %>
             <label class="forcheckbox" for="Command_PublishLater"><%=_Encoded("Publish Later")%></label>
         </div>
         <div>
             <label class="forpicker" for="ScheduledPublishUtcDate"><%=_Encoded("Date")%></label>
             <%=Html.EditorFor(m => m.ScheduledPublishUtcDate)%>
    +        <%= Html.ValidationMessage("ScheduledPublishUtcDate")%>
             <label class="forpicker" for="ScheduledPublishUtcTime"><%=_Encoded("Time")%></label>
             <%=Html.EditorFor(m => m.ScheduledPublishUtcTime)%>
    +         <%= Html.ValidationMessage("ScheduledPublishUtcTime")%>
         </div>
     </fieldset>
     <script type="text/javascript">$(function() {
    
    
    

    external by adamlj modified Jan 23, 2014  3463  14  4  0

    MailGun API Python Requests multiple Attachments Send mail with multiple files/attachments with custom file names

    MailGun API Python Requests multiple Attachments Send mail with multiple files/attachments with custom file names: send_mailgun_attachments.py
    requests.post("https://api.mailgun.net/v2/DOMAIN/messages",
                  auth=("api", "key-SECRET"),
                  files={
                      "attachment[0]": ("FileName1.ext", open(FILE_PATH_1, 'rb')),
                      "attachment[1]": ("FileName2.ext", open(FILE_PATH_2, 'rb'))
                  },
                  data={"from": "FROM_EMAIL",
                        "to": [TO_EMAIL],
                        "subject": SUBJECT,
                        "html": HTML_CONTENT
                  })
    
    

    external by Amit Narayanan modified Apr 16, 2015  240  2  3  0

    Pseudo code for uploading attachments to AWS S3

    Pseudo code for uploading attachments to AWS S3: attachment_processor.rb
    # if there are attachments...
    if @email.attachments.present?
      # ...loop over each one...
      @email.attachments.each do |attachment|
    
      # ... and upload to storage provider
      response = storage.put_object($BUCKET_NAME, # S3 bucket
          attachment.original_filename,           # filename
          attachment,                             # the ActionDispatch::Http::UploadedFile object returned by Griddler
          $OPTIONS                                # things like Content-Type headers, S3 acl go here
      )
    end
    
    

    external by subhaze modified Nov 11, 2015  224  0  3  0

    I couldn't find any concrete way of selectively pulling content from an old Wordpress blog (with attachments). So... this python script will take an xml export file of all your Wordpress content and only move over the attachments that are found based o...

    I couldn't find any concrete way of selectively pulling content from an old Wordpress blog (with attachments). So... this python script will take an xml export file of all your Wordpress content and only move over the attachments that are found based on your selective content Wordpress export.: wp_xml_export_mashup.py
    import codecs
    from bs4 import BeautifulSoup
    
    soup_all = BeautifulSoup(open('Wordpress_all_content.xml'))
    soup_all_items = soup_all.find_all('item')
    
    soup_posts = BeautifulSoup(open('Wordpress_selective_content.xml'))
    soup_posts_items = soup_posts.channel.find_all('item')
    
    def match_post(item):
    	for elem in soup_posts_items:
    		if elem.find('wp:post_id').text == item.find('wp:post_parent').text:
    			return True
    	return False
    
    for elem in soup_all_items:
    	if elem.find('wp:post_type').text == 'attachment' and match_post(elem):
    		soup_posts.channel.append(elem)
    
    with codecs.open('new_wp_import.xml', 'w', 'UTF-8') as file:
    	file.write(unicode(str(soup_posts), 'UTF-8'))
    
    
    • Public Snippets
    • Channels Snippets