在Python中使用iCloud发送电子邮件

时间:2019-07-16 14:58:21

标签: python python-3.x smtp icloud smtplib

我正在尝试使用以下代码从iCloud电子邮件地址发送一些电子邮件:

import smtplib


def main():
    smtp_obj = smtplib.SMTP('smtp.mail.me.com', 587)
    smtp_obj.starttls()
    smtp_obj.login('user@icloud.com', 'password')

    pairs = {'name_1': 'email_1@gmail.com', 'name_2': 'email_2@gmail.com'}

    try:
        for name in pairs.keys():
            body = 'hi {}'.format(name)
            print('Sending email to {}...'.format(name))
            send_status = smtp_obj.sendmail(smtp_obj.user, pairs.get(name), body)

            if send_status != {}:
                print('There was a problem sending mail to {}.\n{}'.format(name, send_status))
    except smtplib.SMTPDataError:
        print('Sending email to {} failed.'.format(name))
    finally:
        smtp_obj.quit()


if __name__ == '__main__':
    main()

但是,当我运行它时,我只会收到一个SMTPDataError,说,

smtplib.SMTPDataError: (550, b'5.7.0 From address is not one of your addresses')

我尝试过硬编码不同的地址。当我使用我的地址时,我得到了。当我使用我知道是错误的地址时,错误消息还会打印出无效的电子邮件(此帐户无法访问该电子邮件,例如,列出未登录的gmail地址以查看会发生什么)。 / p>

有人知道这是怎么回事吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。事实证明,“发件人”和“发件人”地址必须作为消息正文的一部分提供,以便icloud发送电子邮件。

我缺少的代码段如下:

try:
    for name in pairs.keys():
        msg = ('From: {}\r\nTo: {}\r\n\r\nHi, {}'.format(smtp_obj.user,
                                                         pairs.get(name),
                                                         name))

        print('Sending email to {} at {}...'.format(name, pairs.get(name)))

        send_status = smtp_obj.sendmail(from_addr=smtp_obj.user,
                                        to_addrs=pairs.get(name),
                                        msg=msg)

        if send_status != {}:
            print('There was a problem sending mail to {}.\n{}'.format(name, send_status))
finally:
    smtp_obj.quit()