Skip to content

Instantly share code, notes, and snippets.

@chrisswanda
Last active January 24, 2024 08:53
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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'] = 'sendfrom@mail.com'
msg['To'] = 'sendto@mail.com'
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('sendfrom@mail.com',
'sendto@mail.com', msg.as_string())
mailserver.quit()
@pratikksinha
Copy link

Hi Chris, I was trying to use the script without importing MIMEMultipart. But I was getting an error as "smtplib.SMTPDataError: (550, b'5.7.0 From address is not one of your addresses')". But after using with MIMEMultipart the code worked like charm. Can you help me understand how this is working and not getting an error.

@pratikksinha
Copy link

Also the sent email is not stored in the Sent Mailbox. How can we achieve that?

@chrisswanda
Copy link
Author

Hi Chris, I was trying to use the script without importing MIMEMultipart. But I was getting an error as "smtplib.SMTPDataError: (550, b'5.7.0 From address is not one of your addresses')". But after using with MIMEMultipart the code worked like charm. Can you help me understand how this is working and not getting an error.

I believe it is due to the from and to addresses must be provided as part of the message body for iCloud to send the message out.

Also the sent email is not stored in the Sent Mailbox. How can we achieve that?

I think you would use imaplib.

Append message to named mailbox.```

```import imaplib
from email.message import Message
from time import time

connection = imaplib.IMAP4_SSL(HOSTNAME)
connection.login(USERNAME, PASSWORD)

new_message = Message()
new_message["From"] = "hello@itsme.com"
new_message["Subject"] = "My new mail."
new_message.set_payload("This is my message.")

connection.append('INBOX', '', imaplib.Time2Internaldate(time()), str(new_message).encode('utf-8'))```

 

@larsinka
Copy link

Hi Chris, do you have any IMAP script as well? Im trying to receive iCloud mails with a python script but it doesn't work. All tutorials use gmail.

@chrisswanda
Copy link
Author

I do not. But if you are using a Google example, I would imagine using iCloud's IMAP settings should work also.

#  Connect to the iCloud IMAP Mail Server
imap.put_Ssl(True)
imap.put_Port(993)
success = imap.Connect("imap.mail.me.com")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

#  The username is usually the name part of your iCloud email address
#  (for example, emilyparker, not emilyparker@icloud.com).
success = imap.Login("ICLOUD_USERNAME","ICLOUD_PASSWORD")
if (success != True):
    print(imap.lastErrorText())
    sys.exit()

@larsinka
Copy link

larsinka commented Feb 1, 2022

I get to the point to actually download a list with all email and am able to read the UIDs but the emails don't contain anything. In all the gmail examples its as easy a calling the fetch method and getting the email with all its payload.
Sorry for not pointing this out in the first place.

@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