Forum Archive

Apple Mail Objc_Util

jbap

How can I send an email with Apple mail through an app that I make?
I assume this will use the objc_util module...

Webmaster4o

You can always use a mailto:// url, see the documentation.

ihf

Presumably you could also construct the email and send it using smtplib without ever invoking the mail app.

alijnclarke

If you could expand a little on what it is you want to do then we could probably come up with some good suggestions :)

cook

@jbap

This is from the objc_util docs. When I ran it, the 'cancel' didn't work! But anyway...

from objc_util import *

# - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
def mailComposeController_didFinishWithResult_error_(_self, _cmd, controller, result, error):
    print 'Mail composer finished'
    # Wrap the controller parameter in an `ObjCInstance`, so we can send messages:
    mail_vc = ObjCInstance(controller)
    # Set delegate to nil, and release its memory:
    mail_vc.setDelegate_(None)
    ObjCInstance(_self).release()
    # Dismiss the sheet:
    mail_vc.dismissViewControllerAnimated_completion_(True, None)

methods = [mailComposeController_didFinishWithResult_error_]
protocols = ['MFMailComposeViewControllerDelegate']
MyMailComposeDelegate = create_objc_class('MyMailComposeDelegate', NSObject, methods=methods, protocols=protocols)

@on_main_thread
def show_mail_sheet():
    MFMailComposeViewController = ObjCClass('MFMailComposeViewController')
    mail_composer = MFMailComposeViewController.alloc().init().autorelease()
    # Use our new delegate class:
    delegate = MyMailComposeDelegate.alloc().init()
    mail_composer.setDelegate_(delegate)
    # Present the mail sheet:
    root_vc = UIApplication.sharedApplication().keyWindow().rootViewController()
    root_vc.presentViewController_animated_completion_(mail_composer, True, None)

if __name__ == '__main__':
    show_mail_sheet()

cook

Another thing that would need to be fixed:
The mail composer view doesn't close after 'send'

JonB

See http://omz-software.com/pythonista/docs/ios/objc_util.html#creating-new-objective-c-classes, and scroll down a little to where MFMailComposeViewController. The user always has to click send (your app cannot send an email in the user's name without their approval). You can pre-fill parts of the message, add attachments, see here.

JonB

@cook
mail_composer.mailComposeDelegate=delegate
instead of the setDelegate_ line.

cvp

If you use

s = smtplib.SMTP('SMTP server ip')
s.sendmail(me, me, msg.as_string())

You don't need to confirm the sending

JonB

Many ISPs now block port 25 as a way to help curtail spam -- in that case you can only smtp through the isp's servers, using authentication.

I gathered the OP was interested in how to present and show the standard ios mail sheet.

cvp

You're right but I only wanted tell him there is another way for! sorry.