我是python的新手,我正在使用python 3。我需要发送一封包含生成消息的电子邮件。消息一切正常(我可以打印它(,但不知何故,在该配置中,不会发送 def-blocks 电子邮件。我做错了什么?我没有收到任何错误通知。
import random
import string
import smtplib
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from@smtp.mailtrap.io"
receiver = "to@smtp.mailtrap.io"
def randomString(stringLength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def randomMessage():
random_string1 = randomString()
random_string2 = randomString()
message = f"""
Subject: {random_string1}
To: {receiver}
From: {sender}
{random_string2}"""
return message
def main():
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
message = randomMessage()
#print(message)
server.sendmail(sender, receiver, message)
if __name__ == '__main__':
main()
问题出在消息类型上。我把它改成了MIMEText,它现在可以工作了。
import random
import string
import smtplib
from email.mime.text import MIMEText
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "my mailtrap login"
password = "my mailtrap pass"
sender = "from@smtp.mailtrap.io"
receiver = "to@smtp.mailtrap.io"
def randomString(stringLength=10):
lettersDigits = string.ascii_lowercase + "0123456789"
return ''.join(random.choice(lettersDigits) for i in range(stringLength))
def makeMessage(subject, content):
message = MIMEText(content)
message["Subject"] = subject
message["From"] = sender
message["To"] = receiver
return message
def randomMessage():
return makeMessage(randomString(), randomString())
def sendMessage(message):
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, message.as_string())