通过Python和googlesmtps发送电子邮件

2024-04-29 22:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的电子邮件是:sarahconnor@gmail.com

我想从johnconnor@skynet.com给我发一封电子邮件。在

我不想远程登录到我的gmail帐户发送电子邮件。在

这就是我需要的:

我是莎拉康纳,我想在我的邮箱(sarahconnor@gmail.com)收到一封来自johnconnor@skynet.com的电子邮件。。。在

所以我用这个脚本:

import requests
import smtplib

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
fromm = "johnconnor@skynet.com"
to = "sarahconnor@gmail.com"
msg['From'] = fromm
msg['To'] = COMMASPACE.join(to)
msg.preamble = 'Our family reunion'

requests.get("http://smtp.gmail.com", verify=False)
s = smtplib.SMTP_SSL("smtp.gmail.com", 587)
s.starttls()
s.login('sarahconnor@gmail.com', 'mypassword12345') #here I login to the SMTP server from Google to be able to send emails...
s.sendmail(fromm, to, msg.as_string())
s.close()

我有以下错误:

^{pr2}$

here来看,我似乎没有任何问题。在

有人知道我该怎么解决这个问题吗?在

谢谢


Tags: tofromimportcom电子邮件emailmsgrequests
2条回答

这将从gmail帐户向任何其他帐户发送邮件

import smtplib
from email.mime.text import MIMEText


class GmailHandler():
    """
    IMPORTANT NOTE:
    in order to access a gmail account with this handler,
    your account needs 'foreign-access' enabled (follow these steps):
    login to the account
    go here > https://accounts.google.com/b/0/DisplayUnlockCaptcha
    press 'Continue'
    Done.
    """

    def __init__(self, gmail, password):
        self.gmail = gmail
        self.password = password

    def send_mail(self, receivers, subject, text):

        if not isinstance(receivers, list):
            receivers = [receivers]

        # Send the message via our own SMTP server, but don't include the envelope header
        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(self.gmail, self.password)

        for receiver in receivers:

            msg = MIMEText(text)
            msg['Subject'] = subject
            msg['From'] = self.gmail
            msg['To'] = receiver
            smtp.sendmail(self.gmail, receiver, str(msg))

        smtp.quit()

使用smtplib.SMTP代替smtplib.SMTP_SSL。在

相关问题 更多 >