2016-04-21 109 views
1

我的电子邮件地址是:[email protected]通过Python和谷歌的SMTP服务器发送电子邮件

我想从[email protected]发送电子邮件给我的。

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

这就是我需要:

我萨拉·康纳,我想收到我的邮箱([email protected]),从[email protected]电子邮件...

所以我已经使用该脚本可以这样做:

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 = "[email protected]" 
to = "[email protected]" 
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('[email protected]', '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() 

我有以下错误:

raise ConnectionError(err, request=request) 
requests.exceptions.ConnectionError: ('Connection aborted.', error(10054, 'An existing connection was forcibly closed by the remote host')) 

而从here可以看出,我似乎没有遇到任何问题。

有谁知道我该如何解决这个问题?

感谢

回答

1

这个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() 
+0

好的谢谢,但那不是我所需要的:(我需要从另一封电子邮件发送一封电子邮件到我的电子邮件......而不是从一个gmail帐户。正如我所说:“我不想远程登录到我的Gmail帐户发送电子邮件。“ – waas1919

1

使用smtplib.SMTP而不是smtplib.SMTP_SSL

相关问题