How do I programmatically send email w/attachment to a known recipient using MAPI in C++? MAPISendMail()

How do I programmatically send email w/attachment to a known recipient using MAPI in C++? MAPISendMail()

By : AsapStar
Date : October 21 2020, 11:12 AM
hope this fix your issue This question is similar, but does not show how to add a recipient. , Oops - I forgot to set
code :

Share : facebook icon twitter icon
How do I programmatically send an email in the same way that I can "Send To Mail Recipient" in Windows Explore

How do I programmatically send an email in the same way that I can "Send To Mail Recipient" in Windows Explore

By : Mathew D
Date : March 29 2020, 07:55 AM
around this issue ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically. , This is my MAPI solution:
code :
#include <tchar.h>
#include <windows.h>
#include <mapi.h>
#include <mapix.h>

int _tmain( int argc, wchar_t *argv[] )
    HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) );

    if ( hMapiModule != NULL )
        LPMAPIINITIALIZE lpfnMAPIInitialize = NULL;
        LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL;
        LPMAPISESSION lplhSession = NULL;

        lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, "MAPIInitialize" );
        lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, "MAPIUninitialize" );
        lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, "MAPILogonEx" );
        lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, "MAPISendDocuments" );

        if ( lpfnMAPIInitialize && lpfnMAPIUninitialize && lpfnMAPILogonEx && lpfnMAPISendDocuments )
            HRESULT hr = (*lpfnMAPIInitialize)( NULL );

            if ( SUCCEEDED( hr ) )
                hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &lplhSession );

                if ( SUCCEEDED( hr ) )
                    // this opens the email client with "C:\attachment.txt" as an attachment
                    hr = (*lpfnMAPISendDocuments)( 0, ";", "C:\\attachment.txt", NULL, NULL );

                    if ( SUCCEEDED( hr ) )
                        hr = lplhSession->Logoff( 0, 0, 0 );
                        hr = lplhSession->Release();
                        lplhSession = NULL;


        FreeLibrary( hMapiModule );

    return 0;
Launching email application (MAPI) from C# (with attachment)

Launching email application (MAPI) from C# (with attachment)

By : Haito-H3
Date : March 29 2020, 07:55 AM
Hope this helps At work we have successfully done this using VSTO.
Here is a snippet of some lines we have running on VISTA with Outlook 2007: (the code is in VB.net).
code :
Imports Outlook = Microsoft.Office.Interop.Outlook
dim MailItem As Microsoft.Office.Interop.Outlook.MailItem

' Lets initialize outlook object '
MailItem = OutlookSession.Application.CreateItem(Outlook.OlItemType.olMailItem)
MailItem.To = mailto

MailItem.Subject = communication.Subject
MailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML
MailItem.HTMLBody = htmlBody

MailItem.Attachments.Add(filename, Outlook.OlAttachmentType.olByValue)

' If True is supplied to Display it will act as modal and is executed sequential. '
    Public ReadOnly Property OutlookSession() As Outlook.NameSpace
            If Not OutlookApplication Is Nothing Then
                Return OutlookApplication.GetNamespace ("MAPI")
                Return Nothing
            End If
        End Get
    End Property
Send an iphone attachment through email programmatically

Send an iphone attachment through email programmatically

By : Illiyan
Date : March 29 2020, 07:55 AM
With these it helps try [mailer addAttachmentData:myData mimeType:@"text/csv" fileName:@"expenses.csv"];
Edit: This is the code I'm using in my app:
code :
- (IBAction) ExportData:(id)sender
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kExportFileName];

    self.timeRecords = [[NSMutableArray alloc] init];
    for (int i=0; i< [self.selectedTimeEntries count]; i++) 
        for (int j=0; j<[[self.selectedTimeEntries objectAtIndex:i] count]; j++) 
            if ([[self.selectedTimeEntries objectAtIndex:i] objectAtIndex:j] == [NSNumber numberWithBool:YES]) 
                [self.timeRecords addObject:[self timeEntriesForDay:[self.uniqueArray objectAtIndex:i] forIndex:j]];

    if( !([self.timeRecords count]!=0))
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"There are no time entries selected!" message:@"Please select at least one time entry before proceeding" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];        
    NSMutableString *csvLine;
    NSError *err = nil;
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = nil;
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###0.##"];
    NSString *formattedNumberString = nil;

    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])        
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

    for (timeEntries *timeEntry in self.timeRecords) {
        csvLine = [NSMutableString stringWithString:timeEntry.client];
        [csvLine appendString:@","];
        [csvLine appendString:timeEntry.category];
        [csvLine appendString:@","];
        [csvLine appendString:timeEntry.task];
        [csvLine appendString:@","];
        dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeEntry.date]];
        [csvLine appendString:dateString];
        [csvLine appendString:@","];
        formattedNumberString = [numberFormatter stringFromNumber:timeEntry.duration];
        [csvLine appendString:formattedNumberString];
        [csvLine appendString:@","];
        [csvLine appendString:timeEntry.description];
        [csvLine appendString:@"\n"];

        if([[NSFileManager defaultManager] fileExistsAtPath:filePath])        
            NSString *oldFile = [[NSString alloc] initWithContentsOfFile:filePath];
            [csvLine insertString:oldFile atIndex:0];
            BOOL success =[csvLine writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:&err];

            [oldFile release];
    if (!appDelegate.shouldSendCSV) {
    self.csvText = csvLine;
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])        
        [self emailExport:filePath];
    self.selectedTimeEntries =nil;
    self.navigationController.toolbarHidden = NO;

- (void)emailExport:(NSString *)filePath
    NSLog(@"Should send CSV = %@", [NSNumber numberWithBool:appDelegate.shouldSendCSV]);
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;

    // Set the subject of email
    [picker setSubject:@"My Billed Time Export"];

    // Add email addresses
    // Notice three sections: "to" "cc" and "bcc"   

    NSString *valueForEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@"emailEntry"];
    NSString *valueForCCEmail = [[NSUserDefaults standardUserDefaults] stringForKey:@"ccEmailEntry"];
    if( valueForEmail == nil ||  [valueForEmail isEqualToString:@""])
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Please set an email address before sending a time entry!" message:@"You can change this address later from the settings menu of the application!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];        

    else {
        [picker setToRecipients:[NSArray arrayWithObjects:valueForEmail, nil]];

    if(valueForCCEmail != nil || ![valueForCCEmail isEqualToString:@""])
        [picker setCcRecipients:[NSArray arrayWithObjects:valueForCCEmail, nil]];

    // Fill out the email body text
    NSString *emailBody = @"My Billed Time Export File.";

    // This is not an HTML formatted email
    [picker setMessageBody:emailBody isHTML:NO];

    if (appDelegate.shouldSendCSV) {

    // Create NSData object from file
    NSData *exportFileData = [NSData dataWithContentsOfFile:filePath];

    // Attach image data to the email 
    [picker addAttachmentData:exportFileData mimeType:@"text/csv" fileName:@"MyFile.csv"];
    } else {
        [picker setMessageBody:self.csvText isHTML:NO];
    // Show email view  
    [self presentModalViewController:picker animated:YES];

    // Release picker
    [picker release];
How to send email with attachment in Android Programmatically sdk 4.0

How to send email with attachment in Android Programmatically sdk 4.0

By : brian
Date : March 29 2020, 07:55 AM
this one helps. In my application I want to send email programmatically with out user intervention. I have googled alot and came up with some helpful links given below. But none of them are working for me. , Add below lines to your Import.
code :
import javax.mail.PasswordAuthentication;
How to send a MAPI email with an attachment to a fax recipient?

How to send a MAPI email with an attachment to a fax recipient?

By : user3792237
Date : March 29 2020, 07:55 AM
Hope that helps Ok, your update points towards the attachment, so I'm going to put in another guess: try setting the filetype of the attachment explicitly to 'application/pdf' (your current code doesn't set the lpFileType field). The fax handling might be dependent on that. You can just leave the encoding parts of the MapiFileTagExt (the type lpFileType points to) blank, simply FillChar the record and set cbTag and lpTag fields.
If you need code (the mapi structures can be a bit dazzling at times) just yell, but it'll take me some time to find a moment to type it up.. And anyway, again, I'm just guessing. I don't have a fax setup in my home environment, otherwise I'd do some proper testing.
Related Posts Related Posts :
  • How to use priority_queue with a non-static compare method of class instance?
  • Template parameters inside and outside class/struct
  • Determining prime number
  • How to resolve ambiguity between constructors taking std::string and std::vector
  • My program crashes when I try to change private values from an object
  • Unordered_map with custom class as key
  • Strict aliasing rules broken with templates and inheritance
  • C++ Derived Class Override Return Type
  • singly linked list c++ constructor, destructor and printing out
  • How to clone class with vector of unique_ptr to base class
  • error: no match for operator
  • std::vector doesnt accept my struct as template
  • selection of people's contours
  • how to fix the (Error using mexOpenCV) on matlab?
  • Is or was there a proposal for c++ to use the context for short enum values?
  • Fair assumptions about std::hash implementations
  • undefined reference to libusb using cyusb
  • Function returns null pointer instead of address
  • C++17 copy elision and object destruction
  • Input multiple strings via operator>> c++
  • Avoiding overflow boost container
  • How to Write a Lambda Wrapping a Function with Optional Return Value
  • Partial specialization with more template parameters
  • How to convert fixed size array to pointer on pointer array
  • Memory leak in const member constructor with tag dispatching
  • C++ function with a generic and optional class
  • Custom QGraphicsItem That Contains Child QGraphicsItems
  • Are There Restrictions on What can be Passed to auto Template Parameters?
  • Rotating line inside rectangle bounds
  • Why do I need dynamic memory allocation if I can just create an array?
  • How can I convert a text file into a form that MPI_Bcast can send?
  • How to get array of all `this` of an instance
  • Using pointers as parameters
  • Automatic type deduction with const_cast is not working
  • Why does std::is_rvalue_reference not do what it is advertised to do?
  • Function Template Specialization with Forward Declared Type
  • template deduction failed in vector
  • Is there a signed `sizeof` alternative in Qt
  • clarification on overloading the -> operator
  • What is __m128d?
  • QtConcurrent: why releaseThread and reserveThread cause deadlock?
  • Function receiving different value than passed
  • Can C++ close a '''fstream''' variable after '''.close()'''?
  • Is it necessary to overload operator in this specific case
  • Comparing an element of a string array with a string
  • how to dereference a pointer of a map of pointers to objects in c++
  • How recursive function control flow change for static variable?
  • SDL 2 blitting BMP File
  • Why does an extremely large value cause this code to repeat infinitely?
  • Function returning different value than what is in function body before return statement
  • Struggling with including Headers in another header file (C++)
  • WebViewProcessControl initialization crash
  • C++ exception 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00C02F30)
  • What's difference between forward and move in the constructor of class?
  • C++: Is it possible to condense `bool` objects within the same byte?
  • I cant understand this access modifier
  • Boost Spirit X3: Collapsing one-element lists
  • How can I add a char to an istringstream?
  • Wrapping variadic templates in pybind11
  • C++ referencing instances created within a function's scope
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org