python:發送郵件

來源:互聯網
上載者:User

#!/usr/bin/python
# -*- coding: utf-8 -*-

import smtplib
import sys, datetime
import email.mime.text
from email.mime.base import MIMEBase
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import time, os

class EmailProcess(object):
@staticmethod
def SendEmail(head="", body="", attachment=""):
# my test mail
mail_username='user_name@163.com'
mail_password='password'
from_addr = mail_username
to_addrs=('to_user@163.com')

# HOST & PORT
HOST = 'smtp.163.com'
PORT = 25

# Create SMTP Object
smtp = smtplib.SMTP()
# print 'connecting ...'

# show the debug log
smtp.set_debuglevel(1)

# connet
try:
print smtp.connect(HOST,PORT)
except:
print 'CONNECT ERROR ****'

# gmail uses ssl
# smtp.starttls()
# login with username & password

try:
print 'loginning ...'
smtp.login(mail_username,mail_password)
except:
print 'LOGIN ERROR ****'

# fill content with MIMEText's object

msg = MIMEMultipart()

# add attachment
att_list = attachment.strip().split(',')
for att_item in att_list:
if att_item.strip() and os.path.exists(att_item.strip()):
att = email.mime.text.MIMEText(open(att_item.strip(),'rb').read(), 'base64', 'gb2312')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename=\"' + att_item.strip() + "\""
msg.attach(att)

msg['From'] = from_addr
msg['To'] = ';'.join(to_addrs)
msg['Subject']= Header(head, 'gb2312')
msg['Date'] = time.strftime("%a, %d %m %Y %H:%M:%S %z")
body = MIMEText(head, _charset='gb2312')
msg.attach(body)

smtp.sendmail(from_addr,to_addrs,msg.as_string())
smtp.quit()

if __name__ == '__main__':
head = "buyoffer stopped(" + str(datetime.datetime.now()) + "), max_aliid: "
print "len(sys.argv)", len(sys.argv)
if len(sys.argv) >= 2:
aliid = sys.argv[1]
else:
aliid = "none"

head = head + aliid
EmailProcess.SendEmail(head=head)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.