Skip to content

Instantly share code, notes, and snippets.

@chrisswanda
Last active January 10, 2025 10:14
Show Gist options
  • Save chrisswanda/57fbc7c587f76d8437880657c0893009 to your computer and use it in GitHub Desktop.
Save chrisswanda/57fbc7c587f76d8437880657c0893009 to your computer and use it in GitHub Desktop.
Python script to send mail via Apple's iCloud. Be sure to setup an app specific password for and do not use or expose your iCloud password. https://support.apple.com/en-us/HT204397
import smtplib
#email.mime.multipart is specific to python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Subject'
message = 'Message body'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.mail.me.com', 587)
# identify ourselves
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('iCloud ID', 'app-specific password')
mailserver.sendmail('[email protected]',
'[email protected]', msg.as_string())
mailserver.quit()
@chrisswanda
Copy link
Author

chrisswanda commented Feb 1, 2022

Maybe try something like this?

#  Once the folder/mailbox is selected, the NumMessages property
#  will contain the number of emails in the mailbox.
#  Loop from 1 to NumMessages to fetch each email by sequence number.

n = imap.get_NumMessages()
bUid = False
for i in range(1,(n)-1):

    #  Download the email by sequence number.

    email = imap.FetchSingle(i,bUid)
    if (imap.get_LastMethodSuccess() != True):
        print(imap.lastErrorText())
        sys.exit()

    print(str(i) + ": " + email.ck_from())
    print("    " + email.subject())
    print("-")

#  Disconnect from the IMAP server.
success = imap.Disconnect()

@larsinka
Copy link

larsinka commented Feb 1, 2022

What example did you use?

.get_NumMessages is not an IMAP4 command for me.

Exception has occurred: AttributeError
Unknown IMAP4 command: 'get_NumMessages'
File "/Users/lars/Desktop/Test/Test-Env/src/email.py", line 25, in
n = mail.get_NumMessages()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment