Python: send emails

Source: Internet
Author: 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 'ing ing ...'

# Show the debug log
SMTP. set_debuglevel (1)

# Connet
Try:
Print SMTP. Connect (host, Port)
Except t:
Print 'connect error ****'

# Gmail uses SSL
# SMTP. starttls ()
# Login with username & Password

Try:
Print 'loginning ...'
SMTP. login (mail_username, mail_password)
Except t:
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 ['subobject'] = 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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.