【问题标题】:sending email using python using smtp使用 smtp 使用 python 发送电子邮件
【发布时间】:2018-10-23 22:10:10
【问题描述】:

我正在尝试通过 python 使用 SMTP 发送电子邮件。 这是我的代码:

import smtplib
from email.mime.text import MIMEText

textfile='msg.txt'
you='ashwin@gmail.com'
me='ashwin@gmail.com'

fp = open(textfile, 'rb')
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
print "reached before s"
s = smtplib.SMTP('127.0.0.1',8000)
print "reached after s"
s.sendmail(me, [you], msg.as_string())
s.quit()

当我尝试执行此代码时,会打印“在 s 之前到达”,然后进入一个无限循环左右,即“在 s 之后到达”不会打印并且程序仍在运行。 这是服务器的代码:

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"


if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)



HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

有人能找出问题所在吗?

【问题讨论】:

  • 您的机器 (127.0.0.1) 的端口 8000 上没有运行 SMTP 服务器。您有一个 Web 服务器 (HTTP)。我在这里回答了一个问题:stackoverflow.com/a/23047183/289011 看看。这可能会有所帮助。
  • @BorrajaX 根据我的回答,yagmail 可能对您也很感兴趣 :)

标签: python email smtp


【解决方案1】:

我相信yagmail(免责声明:我是维护者)对你有很大帮助。

它的目标是让发送带有附件的电子邮件变得容易。

import yagmail
yag = yagmail.SMTP('ashwin@gmail.com', 'yourpassword')
yag.send(to = 'ashwin@gmail.com', subject ='The contents of msg.txt', contents = 'msg.txt')

确实只有三行。

请注意,yagmail contents 将尝试加载传递的字符串。如果不能,它将作为文本发送,如果它可以加载,它将附加它。

如果您传递一个字符串列表,它会尝试将每个字符串加载为一个文件(或者再次显示文本)。

使用pip install yagmailpip3 install yagmail 安装Python 3。

更多信息请访问github

【讨论】:

    【解决方案2】:

    这是一种不同的方法,它创建了一个电子邮件发件人类,并处理了所有错误处理:

    import getpass
    import smtplib
    
    class EmailBot(object):
        # Gets the username and password and sets up the Gmail connection
        def __init__(self):
            self.username = \
                raw_input('Please enter your Gmail address and hit Enter: ')
            self.password = \
            getpass.getpass('Please enter the password for this email account and hit Enter: ')
            self.server = 'smtp.gmail.com'
            self.port = 587
            print 'Connecting to the server. Please wait a moment...'
    
            try:
                self.session = smtplib.SMTP(self.server, self.port)
                self.session.ehlo()  # Identifying ourself to the server
                self.session.starttls()  # Puts the SMTP connection in TLS mode. All SMTP commands that follow will be encrypted
                self.session.ehlo()
            except smtplib.socket.gaierror:
                print 'Error connecting. Please try running the program again later.'
                sys.exit() # The program will cleanly exit in such an error
    
            try:
                self.session.login(self.username, self.password)
                del self.password
            except smtplib.SMTPAuthenticationError:
                print 'Invalid username (%s) and/or password. Please try running the program again later.'\
                     % self.username
                sys.exit() # program will cleanly exit in such an error
    
            def send_message(self, subject, body):
                try:
                    headers = ['From: ' + self.username, 'Subject: ' + subject,
                       'To: ' + self.username, 'MIME-Version: 1.0',
                       'Content-Type: text/html']
                    headers = '\r\n'.join(headers)
    
                    self.session.sendmail(self.username, self.username, headers + '''\r\r''' + body)
                except smtplib.socket.timeout:
                    print 'Socket error while sending message. Please try running the program again later.'
                    sys.exit() # Program cleanly exits
                except:
                    print "Couldn't send message. Please try running the program again later."
                    sys.exit() # Program cleanly exits
    

    您需要做的就是创建一个 EmailBot 实例并在其上调用 send_message 方法,并将适当的详细信息作为输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2015-11-10
      • 2023-03-09
      • 2013-08-16
      相关资源
      最近更新 更多