[b]一、直接调用命令行发送邮件(以及shell中sendEmail)[/b]
问题:主题为中文时乱码
主题乱码,网上找了很多,基本上可以确认是头文件编码的问题,通过对主题进行base64编码可以解决这个问题,实现如下:
直接用shell发送邮件的代码如下
补充: 正文的换行符是
如果是ssh调用其他的邮件服务器来发邮件,命令要ssh命令要用双引号括起来,否则换行字符不识别
[b]二、使用SMTP协议发送邮件[/b]
问题:主题为中文时乱码
主题乱码,网上找了很多,基本上可以确认是头文件编码的问题,通过对主题进行base64编码可以解决这个问题,实现如下:
# 发送email,username用户名,subject主题,text内容
def send_email(self,username,subject,text):
# 邮件内容为utf-8格式
text = text.encode('utf-8')
# 主题需要进行base64编码在转成utf8,注意后面这个strip,否则又出现一个换行符
subject = "=?UTF-8?B?%s?=" % base64.encodestring(subject).strip()
cmd = "/usr/bin/sendEmail -f test@yoursite.com -t %s -o message-charset=utf-8 -u \"%s\" -m \"%s\" " % (username,subject,text)
try:
rt = os.popen(cmd).read().split()
return True
except Exception,e:
return False
直接用shell发送邮件的代码如下
subject=`echo -n 任务异常 | base64`
test_time=20130123
sendEmail -f aaa@xxx.com -t target@target.com -o message-charset=utf-8 -u "=?UTF-8?B?${subject}?=" -m "已经存在任务,${test_time}的任务取消进行"
补充: 正文的换行符是
\n
如果是ssh调用其他的邮件服务器来发邮件,命令要ssh命令要用双引号括起来,否则换行字符不识别
ssh root@**** "sendemai -o ...."
[b]二、使用SMTP协议发送邮件[/b]
newusers = 'aaaaaa@xxx.com;cccc@xx.com'
newccs = 'bbbbb@xxx.com;adfadf@xxx.com'
text = '测试邮件'
mail_host = 'smtp.xxx.com'
mail_user = 'xxx_service'
mail_user_full = 'xxx_service@xxx.com'
mail_pwd = '密码'
mail_bcc = ''
#表头信息
msg = MIMEText(text,'base64', 'utf-8')
msg['From'] = mail_user_full
msg['Subject'] = subject
msg['To'] = newusers
msg['Cc'] = newccs
msg['Bcc'] = ''
try:
s = smtplib.SMTP()
s.connect(mail_host,'25')
#login
s.login(mail_user,mail_pwd)
#send mail
print newusers
print newccs
print msg.as_string()
# 邮件人发送和抄送统一放在一起发送,需要在上面的标头信息中进行区分
s.sendmail(mail_user_full,newusers.split(';')+newccs.split(';')+mail_bcc.split(";"),msg.as_string())
s.close()
print 'success'
# print rt
return True
except Exception,e:
# print 'email error'
print e
return False