使用python 编写一段邮件发送代码‘’
时间: 2024-03-11 08:18:05 浏览: 72
好的,以下是使用 Python 发送邮件的代码:
```python
import smtplib
from email.mime.text import MIMEText
# 发送邮箱地址
from_addr = '你的邮箱地址'
# 邮箱授权码,不是登录密码
password = '你的邮箱授权码'
# 接收邮箱地址
to_addr = '接收邮箱地址'
# 邮件主题
subject = 'Python 发送邮件测试'
# 邮件内容
msg = MIMEText('测试邮件,收到请回复!', 'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
# 发送邮件
try:
server = smtplib.SMTP_SSL('smtp.qq.com', 465)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
print('邮件发送成功!')
except Exception as e:
print('邮件发送失败:', e)
finally:
server.quit()
```
希望可以帮助到你,如果你有更多的问题,可以随时问我哦~
相关问题
用python的yagmail编写一段发送html附件代码
好的,以下是使用 yagmail 发送 html 附件的代码示例:
```python
import yagmail
# 配置发件人账号信息
sender_email = "your_sender_email@example.com"
sender_password = "your_sender_password"
# 配置收件人信息
receiver_email = "recipient_email@example.com"
# 配置邮件内容
subject = "这是一封带有 HTML 附件的邮件"
contents = "这是一封带有 HTML 附件的邮件,请查收。"
# 读取 HTML 文件内容
with open("test.html", "r", encoding="utf-8") as f:
html_content = f.read()
# 配置邮件附件
attachments = ["test.html"]
# 发送邮件
yag = yagmail.SMTP(user=sender_email, password=sender_password)
yag.send(to=receiver_email, subject=subject, contents=[contents, html_content], attachments=attachments)
yag.close()
```
请注意,代码中的 `your_sender_email@example.com` 和 `your_sender_password` 分别对应着发件人的email和密码,需要替换为实际的值。附件的文件名和路径也需要替换成实际的值。
用python写一段代码,flask 异步发送带附件的邮件
以下是用 Python 编写的 Flask 异步发送带附件的邮件的代码:
```python
from flask import Flask, render_template, request
from flask_mail import Mail, Message
from threading import Thread
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME='your_email@gmail.com',
MAIL_PASSWORD='your_password'
)
mail = Mail(app)
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send_email', methods=['POST'])
def send_email():
recipient = request.form['recipient']
subject = request.form['subject']
body = request.form['body']
attachment = request.files['attachment']
msg = Message(subject, sender='your_email@gmail.com', recipients=[recipient])
msg.body = body
msg.attach(attachment.filename, attachment.read(), attachment.content_type)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return 'Email sent!'
if __name__ == '__main__':
app.run()
```
请注意,这只是一个示例代码,您需要将其适当修改以适应您的需求。
阅读全文