[英]sending email using smtplib and SSL but receiver is no receiving it
I am trying to send email from one email to another using smtplib and ssl.我正在尝试使用 smtplib 和 ssl 将 email 从一个 email 发送到另一个。 It's showing delivered, but there is no email at receiver end.它显示已交付,但接收端没有 email。 I am trying two different codes:我正在尝试两种不同的代码:
Code 1:代码 1:
import smtplib, ssl
port = 465
smtp_server = "myserver.com"
sender_email = "sender@myserver.com"
receiver_email = "receiver@gmail.com"
password = "mypassword"
message = """\
Subject: Hi there
This message is sent from Python."""
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print("Sent..")
except:
print("Error!!")
code 2:代码2:
import smtplib
import os.path
from email.mime.text import MIMEText
msg = MIMEText("")
msg['Subject'] = "Hi there, This message is sent from Python."
s = smtplib.SMTP_SSL("myserver.com:465")
s.login("sender@myserver.com","mypassword")
s.sendmail("sender@myserver.com","receiver@gmail.com", msg.as_string())
s.quit()
print("done")
Can not find the problem.找不到问题。 Any idea?任何想法?
The sendmail
method is a low level method that assumes that the message text is correctly formatted. sendmail
方法是一种低级方法,它假定消息文本的格式正确。 And your messages do not contain the usual To:
and From:
headers.而且您的消息不包含通常的To:
和From:
标头。
The send_message
method uses an EmailMessage
and formats it correctly, so it can be easier to use. send_message
方法使用EmailMessage
并正确格式化它,因此它更易于使用。 I would advise to change your code to:我建议将您的代码更改为:
port = 465
smtp_server = "myserver.com"
password = "mypassword"
msg = MIMEText("This message is sent from Python.")
msg['Subject'] = "Hi there"
msg['From'] = "sender@myserver.com"
msg['To'] = "receiver@gmail.com"
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.send_message(msg)
print("Sent..")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.