问题:当我向用户发送邮件时,从未在用户收件箱中看到的用户名只显示email-id但我需要发件人的用户名
来自:demo@gmail.com 用户名:演示
致:demotest@gmail.com
import smtplib
fromaddr = From
toaddrs = To
msg = 'Why,Oh why!'
username = From
password = *******
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
答案 0 :(得分:2)
smtplib
不会自动包含任何标头,并且您需要添加From:
标头,因此您必须自行安装以下内容:
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
% (fromaddr, ", ".join(toaddrs)))
您可以在DOCS。
中找到答案 1 :(得分:1)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
fromaddr = 'demo@gmail.com'
toaddrs = 'demotest@gmail.com'
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "good morning" #like name
msg['To'] = "GGGGGG"
body = MIMEText("example email body")
msg.attach(body)
username = 'demo@gmail.com'
password = ''
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
答案 2 :(得分:0)
您只需要正确创建消息即可。我认为最方便的方法是使用一个特殊的消息对象。我放了一个类,可能可以帮助你在项目中发送消息。
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
class EmailSender(object):
def __init__(self, subject, to, config):
self.__subject = subject
self.__to = tuple(to) if hasattr(to, '__iter__') else (to,)
self.__from = config['user']
self.__password = config['password']
self.__server = config['server']
self.__port = config['port']
self.__message = MIMEMultipart()
self.__message['Subject'] = self.__subject
self.__message['From'] = self.__from
self.__message['To'] = ', '.join(self.__to)
def add_text(self, text):
self.__message.attach(
MIMEText(text)
)
def add_image(self, img_path, name=None):
if name is None:
name = os.path.basename(img_path)
with open(img_path, 'rb') as f:
img_data = f.read()
image = MIMEImage(img_data, name=name)
self.__message.attach(image)
def send(self):
server = smtplib.SMTP_SSL(self.__server, self.__port)
server.login(self.__from, self.__password)
server.sendmail(self.__from, self.__to, self.__message.as_string())
server.close()
sender = EmailSender("My letter", "my_target@email", {
'user': "from@email",
'password': "123456",
'server': "mail.google.com"
'port': 465
})
sender.add_text("Why,Oh why!")
sender.send()
答案 3 :(得分:0)
或者通过安装yagmail和
轻松实现假设:
To = 'someone@gmail.com'
From = 'me@gmail.com'
pwd = '******'
alias = 'someone'
执行命令
import yagmail
yag = yagmail.SMTP(From, pwd)
yag.send({To: alias}, 'subject', 'Why,Oh why!')
安装可能由pip install yagmail