一: 利用python包
Python分别提供了收发邮件的库,smtplib、poplib和imaplib。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
发送邮件
:param SMTP_host: smtp.163.com
:param from_addr: 发送地址:[email protected]
:param password: 邮箱的授权码
:param to_addrs: 发送给谁的邮箱: [email protected]
:param subject: 邮件主题: test
:param content: 邮件内容: test
:return: None
"""
import smtplib
import email.mime.multipart
import email.mime.text
def send_email(SMTP_host, from_addr, password, to_addrs, subject='', content=''):
msg = email.mime.multipart.MIMEMultipart()
msg['from'] = from_addr
msg['to'] = to_addrs
msg['subject'] = subject
content = content
txt = email.mime.text.MIMEText(content)
msg.attach(txt)
smtp = smtplib.SMTP()
smtp.connect(SMTP_host, '25')
smtp.login(from_addr, password)
smtp.sendmail(from_addr, to_addrs, str(msg))
smtp.quit()
send_email('smtp.163.com', '发件人的163邮箱地址', '163邮箱的授权码', '收件邮箱地址', '主题', '内容')
param password: 邮箱的授权码
二: 利用shell命令
1. 安装
sudo apt-get install mailutils
2. 使用
2.1 不带附件
- 一行命令发送邮件
mail -s "Test email from ubuntu server!" [email protected] <<< 'Here is the message body.'
或
echo 'Here is the message body.' | mail -s "Test email from ubuntu server!" [email protected]
Test email from ubuntu server 是邮件的主题.
Here is the message body 是邮件的正文. - 使用mail的命令提示发送邮件
给[email protected] 发送邮件,并抄送给[email protected]。邮件主题为Test Subject,内容为Merry christmas
mail -s 'Test Subject' [email protected]
输入该命令后回车,提示Cc:,这时输入抄送邮件地址[email protected],然后回车。
继续输入邮件正文内容Merry christmas,正文输入结束后,按Ctrl-D 结束输入并发送邮件。 - 从文件中读取内容并发送
mail -s 'Text message' [email protected] < /home/user/message.txt
从message.txt中读取内容并发送. - 给多个邮箱发送邮件
mail -s 'Subject' [email protected],[email protected],[email protected] < message.txt
- 指定发件人姓名和地址
echo "This is the message body" | mail -s "subject" [email protected] -aFrom:[email protected]
或
echo "This is the message body" | mail -s "subject" [email protected] -aFrom:John\
2.2 带附件
echo "This is the message body" | mail -s "subject" [email protected] -A /path/to/attached_file