python - 在 Python 中使用 SMTP 发送电子邮件

标签 python email crash smtp smtplib

我正在做一个制作我自己的即时通讯程序的项目,即使没有图形或任何东西,只是为了了解Python中的内置模块。 在这里,我尝试编写一段代码,让用户输入所需的用户名和密码,然后(向用户)发送一封电子邮件,其中包含一个 12 个字符的随机字符串,用户将将其输入回程序。不知何故,当我运行代码时,我的整个计算机卡住了! 代码如下:

import smtplib
SMTPServer = smtplib.SMTP("smtp.gmail.com",587)
SMTPServer.starttls()
SMTPServer.login(USERNAME, PASSWORD)*

userEmail = raw_input("Please enter your e-mail: ")
if verifyEmail(userEmail) == False:
    while True:
        userEmail = raw_input("Error! Please enter your e-mail: ")
        if verifyEmail(userEmail) == True:
            break

randomString = generateRandomString()
message = """From: From Person <%s>
To: To Person <%s>
Subject: Ido's IM Program Registration

Your registration code is: %s
""" %(SERVEREMAIL, userEmail, randomString)

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(SERVEREMAIL, userEmail, message)
   print "Successfully sent email"
except smtplib.SMTPException:
   print "Error: unable to send email"

inputString = raw_input("Input generated code sent: ")

最佳答案

这是 smtp 客户端的工作示例。 你的代码在哪里阻塞?

# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText


class SMTPClient(object):
    def __init__(self, recepient, subject, body):
        self.recepient = recepient
        self.subject = subject
        self.body = body
        self.mail_host = conf.get('smtp_server.host')
        self.mail_port = conf.get('smtp_server.port')
        self.username = conf.get('account.username')
        self.password = conf.get('account.password')
        self.mail_sender = conf.get('account.from')
        self._setup()

    def _setup(self):
        self.smtp_client = smtplib.SMTP(self.mail_host, self.mail_port)
        self.smtp_client.ehlo_or_helo_if_needed()
        self.smtp_client.starttls()
        self.smtp_client.login(self.username, self.password)
        self._send_mail()

    def _make_mail(self):
        message = MIMEText(self.body, _charset='utf-8')
        message['From'] = self.mail_sender
        message['To'] = self.recepient
        message['Subject'] = self.subject
        return message.as_string()

    def send_mail(self):
        self.smtp_client.sendmail(self.mail_sender, self.recepient, self._make_mail())
        self.smtp_client.quit()

关于python - 在 Python 中使用 SMTP 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727345/

相关文章:

python - 如何正确读取 pandas 中的 excel 合并标题单元格

Python:什么是 'from import * safe' 模块?

java - 使用 Java 发送电子邮件

iphone - 从我的应用程序中启动时,字符被邮件应用程序切断

android-studio - Android Studio 每次都会导致蓝屏

android - 应用在设备上启动时出现 NullPointerException

python - 使用 python 中的键访问 csv 行中的每个单元格

python - AddN 必须与 tf.estimator.LinearClassifier 具有相同的大小和形状

email - Rails 3 检查电子邮件地址是否真实

objective-c - 在 Snow Leopard 上运行时程序崩溃