python发送邮件最短代码
时间: 2023-10-13 21:20:22 浏览: 36
可以使用Python的smtplib和email库来发送邮件。以下是一个最短的Python发送邮件的示例代码:
``` python
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('邮件正文')
msg['Subject'] = '邮件标题'
msg['From'] = '发件人邮箱'
msg['To'] = '收件人邮箱'
s = smtplib.SMTP('smtp服务器地址')
s.login('发件人邮箱', '邮箱密码')
s.sendmail('发件人邮箱', ['收件人邮箱'], msg.as_string())
s.quit()
```
请注意,需要填写SMTP服务器地址、发件人邮箱、收件人邮箱和邮箱密码等信息才能成功发送邮件。
相关问题
python发送邮件最短实例
好的,以下是Python发送邮件最短实例:
```python
import smtplib
from email.mime.text import MIMEText
# 设置服务器地址和端口号
mail_host = 'smtp.example.com'
mail_port = 465
# 设置发件人邮箱账号密码
mail_user = 'your_email@example.com'
mail_pass = 'your_email_password'
# 设置收件人邮箱地址
receivers = ['receiver1@example.com', 'receiver2@example.com']
# 创建一个简单文本邮件内容对象
message = MIMEText('这是一封测试邮件')
# 设置邮件内容的发件人、收件人、主题等信息
message['From'] = mail_user
message['To'] = ','.join(receivers)
message['Subject'] = '测试邮件'
# 发送邮件
with smtplib.SMTP_SSL(mail_host, mail_port) as smtp:
smtp.login(mail_user, mail_pass)
smtp.sendmail(mail_user, receivers, message.as_string())
```
请注意,邮件服务器地址和端口号可以根据需要进行修改。同时,也需要确认发件人邮箱账号密码的正确性。
python 发送邮件的代码
以下是使用Python发送邮件的示例代码:
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 邮件发送方的信息:发件人地址,SMTP服务器地址,邮箱授权码
sender = 'your_email_address'
smtp_server = 'smtp.server.com'
password = 'your_email_password'
# 邮件接收方的信息:收件人地址
receiver = 'recipient_email_address'
# 邮件内容
subject = '邮件标题'
body = '邮件正文'
# 创建邮件对象并设置相关字段
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 发送邮件
try:
smtp_obj = smtplib.SMTP(smtp_server, 587)
smtp_obj.starttls()
smtp_obj.login(sender, password)
smtp_obj.sendmail(sender, [receiver], message.as_string())
smtp_obj.quit()
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败:{}'.format(e))
```
需要注意的是,需要替换掉代码中的以下字段:
- `sender`:发件人地址
- `smtp_server`:SMTP服务器地址
- `password`:邮箱授权码
- `receiver`:收件人地址
- `subject`:邮件标题
- `body`:邮件正文
另外,这里使用的是SMTP协议发送邮件,因此需要保证SMTP服务器地址和端口号的正确性,同时需要开启SMTP服务和邮箱的SMTP授权。