首页 > 解决方案 > 如何在 python 中通过 sendemail 将字符串传递给消息

问题描述

我是 python 新手。这是我的

msg = MIMEMultipart()
msg['From'] = "email1"
msg['To'] = "email2"
msg['Subject'] = "Item Found!"
password = "pw"

body = "<a href = ""www.ebay.ca"">Item found!</a>"
msg.attach(MIMEText(body, 'html'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(msg['From'], password)
print("Login success")

server.sendmail(msg['From'], msg['To'], msg.as_string())

我有一个清单是

url1 = "www.ebay.ca"
url2 = "www.amazon.ca"
list = [url1, url2]
i = 0

我要换货

 body = "<a href = ""www.ebay.ca"">Item found!</a>"

 body = "<a href = list[i]>Item found!</a>"

这样做的正确方法是什么,因为我想做一个循环并将 i 作为动态变量并将消息中的 url 作为 url 输出,谢谢。

标签: python

解决方案


您可以使用 . 添加字符串+

tmp = 'str2'
str = 'str1' + tmp + 'str3'
str
>>> 'str1str2str3'

因此只写

body = "<a href = "+ list[i] + ">Item found!</a>"

或者,从 python 3.6 开始,您可以使用 f-strings。

body = f"<a href = {list[i]}>Item found!</a>"

完整代码如下所示:

urls = [url1, url2]
for url in urls:
    body = body = f"<a href = {url}>Item found!</a>"
    # do sth with body




 

推荐阅读