Example #1
0
# from_addr = input("From: ")
# password = input("Password: "******"To: ")
# smtp_sever = input("SMTP server: ")
from_addr = '@163.com'
password = ''
to_addr = ['@126.com', '@gmail.com', '@outlook.com']
smtp_sever = 'smtp.163.com'

msg = MIMEMultipart()
msg['From'] = _format_addr('Pythoner 骆<%s>' % from_addr)

msg['To'] = ";".join(
    (_format_addr('喵<%s>' % to_addr[0]), _format_addr('骆<%s>' % to_addr[1]),
     _format_addr('马各<%s>' % to_addr[2])))
msg['Subject'] = Header('From SMTP 附件', 'utf-8').encode()

#msg.attach(MIMEText("send with file...", 'plain', 'utf-8'))
msg.attach(
    MIMEText(
        '<html><body><h1>Hello (html)</h1>' + '<p><img src = "cid:0"></p>' +
        '<p><img src = "cid:1"></p>' + '</body></html>', 'html',
        'utf-8'))  # cid:X

path = os.path.join(os.path.abspath('.'), 'resource')
with open(os.path.join(path, 'random.jpg'), 'rb') as f:
    mime = MIMEBase('image', 'png', filename='random.jpg')
    mime.add_header('Content-Disposition', 'attachment', filename='random.jpg')
    mime.add_header('Content_ID', '<0>')
    mime.add_header('X-Attachment-ID', '0')
    mime.set_payload(f.read())
Example #2
0
from email.header import Header
import sys

# 设置smtplib所需的参数
# 下面的发件人,收件人是用于邮件传输的。
smtpserver = 'smtp.163.com'
username = '******'
password = '******'
sender = '*****@*****.**'
# 收件人为多个收件人
# receiver = ['*****@*****.**']
receiver = ['*****@*****.**']

# 通过Header对象编码的文本,包含utf-8编码信息和Base64编码信息。以下中文名测试ok
subject = '文件统计'
subject = Header(subject, 'utf-8').encode()

# 构造邮件对象MIMEMultipart对象
# 下面的主题,发件人,收件人,日期是显示在邮件页面上的。
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = 'hawks93jf <*****@*****.**>'
# msg['To'] = '*****@*****.**'
# 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
msg['To'] = ";".join(receiver)
# msg['Date']='2012-3-16'

# 构造文字内容
text = sys.argv[1]
text_plain = MIMEText(text, 'html')
msg.attach(text_plain)
Example #3
0
	for _ in remove:
		remove_log = remove_log + _ + '\n'

	content = ''
	for ip in get_record(record_name):
		num = int(len(ip))
		for i in range(num):
			content = content + '[+] IP :' + ip[i] + '  \n'
	content = '\n' + content + add_log + remove_log
	print content
	send_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

	msg = MIMEText(send_time + '  Network Security Monitor Record : \n' + content, 'plain', 'utf-8')
	msg['From'] = _format_addr(u'Security Monitor <%s>' % from_addr)
	msg['To'] = _format_addr(u'����Ա <%s>' % to_addr)
	msg['Subject'] = Header(u'�����������Ŷ˿ڼ���ձ�', 'utf-8').encode()

	server = smtplib.SMTP(smtp_server, 25)
	server.set_debuglevel(1)
	server.login(from_addr, password)
	server.sendmail(from_addr, [to_addr], msg.as_string())
	server.quit()

def diff_port(result,result1):

	yesday = set() 
	today = set()

	#result = get_record()
	for i in result :
		for _ in i:
Example #4
0
sender = '*****@*****.**'
# receivers = ['*****@*****.**', '*****@*****.**']


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


from_addr = input('From:')
to_addr = input('To:')
msg = MIMEText('python 邮件测试', 'plain', 'utf-8')
# 因为如果包含中文,需要通过Header对象进行编码。
msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
msg['To'] = _format_addr('管理员 <%s>' % to_addr)

Subject = 'python SMTP 测试'
msg['Subject'] = Header('来自smtp的问候...', 'utf-8').encode()

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)
    # 可以打印出和SMTP服务器交互的所有信息
    smtpObj.set_debuglevel(1)
    smtpObj.login(from_addr, mail_pass)
    # 邮件正文是一个str,as_string()把MIMEText对象变成str
    smtpObj.sendmail(from_addr, [to_addr], msg.as_string())
    smtpObj.quit()
    print('邮件发送成功')
except smtplib.SMTPException:
    print('Error:无法发送邮件')
Example #5
0
    def send_email(report_path):
        # 发件人和收件人
        sender = '*****@*****.**'
        receiver = '*****@*****.**'

        # 所使用的用来发送邮件的SMTP服务器
        smtpServer = 'smtp.163.com'

        # 发送邮箱的用户名和授权码(不是登录邮箱的密码)
        username = '******'
        password = '******'

        mail_title = '自动化测试报告'
        # mail_body = '这里是邮件的正文'

        # 创建一个实例
        # msg = MIMEText(mail_body, 'plain', 'utf-8')  # 邮件正文

        msg = MIMEMultipart()
        msg['From'] = sender  # 邮件上显示的发件人
        msg['To'] = receiver  # 邮件上显示的收件人
        msg['Subject'] = Header(mail_title, 'utf-8')  # 邮件主题

        # ---这是文字部分 邮件正文---
        part = MIMEText("接口自动化测试报告")
        msg.attach(part)

        # ---这是附件部分---
        # attach_path = os.path.join(get_base_path(), 'result', 'report.html')
        attach_path = report_path
        part = MIMEApplication(open(attach_path, 'rb').read())
        part.add_header('Content-Disposition',
                        'attachment',
                        filename='report.html')
        msg.attach(part)
        '''
        # xlsx类型附件
        part = MIMEApplication(open('foo.xlsx', 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename="foo.xlsx")
        msg.attach(part)

        # jpg类型附件
        part = MIMEApplication(open('foo.jpg', 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename="foo.jpg")
        msg.attach(part)

        # pdf类型附件
        part = MIMEApplication(open('foo.pdf', 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename="foo.pdf")
        msg.attach(part)

        # mp3类型附件
        part = MIMEApplication(open('foo.mp3', 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename="foo.mp3")
        msg.attach(part)
        '''

        try:
            smtp = smtplib.SMTP()  # 创建一个连接
            smtp.connect(smtpServer)  # 连接发送邮件的服务器
            smtp.login(username, password)  # 登录服务器
            smtp.sendmail(sender, receiver, msg.as_string())  # 填入邮件的相关信息并发送
            print("邮件发送成功!!!")
            smtp.quit()
        except smtplib.SMTPException:
            print("邮件发送失败!!!")
Example #6
0
    def send_email(self, alert):
        """Attempt to send an email for the provided alert, compiling
        the subject and text template and using all the other smtp settings
        that were specified in the configuration file
        """
        contacts = list(OPTIONS['mail_to'])
        LOG.debug('Initial contact list: %s', contacts)
        if 'group_rules' in OPTIONS and len(OPTIONS['group_rules']) > 0:
            LOG.debug('Checking %d group rules' % len(OPTIONS['group_rules']))
            for rule in OPTIONS['group_rules']:
                LOG.info('Evaluating rule %s', rule['name'])
                is_matching = False
                for field in rule['fields']:
                    LOG.debug('Evaluating rule field %s', field)
                    value = getattr(alert, field['field'], None)
                    if value is None:
                        LOG.warning('Alert has no attribute %s',
                                    field['field'])
                        break
                    if self._rule_matches(field['regex'], value):
                        is_matching = True
                    else:
                        break
                if is_matching:
                    # Add up any new contacts
                    new_contacts = [
                        x.strip() for x in rule['contacts']
                        if x.strip() not in contacts
                    ]
                    if len(new_contacts) > 0:
                        if not rule.get('exclude', False):
                            LOG.debug('Extending contact to include %s' %
                                      (new_contacts))
                            contacts.extend(new_contacts)
                        else:
                            LOG.info('Clearing initial list of contacts and'
                                     ' adding for this rule only')
                            del contacts[:]
                            contacts.extend(new_contacts)

        template_vars = {
            'alert': alert,
            'mail_to': contacts,
            'dashboard_url': OPTIONS['dashboard_url'],
            'program': os.path.basename(sys.argv[0]),
            'hostname': os.uname()[1],
            'now': datetime.datetime.utcnow()
        }

        subject = self._subject_template.render(alert=alert)
        text = self._template_env.get_template(
            self._template_name).render(**template_vars)

        if (OPTIONS['email_type'] == 'html' and self._template_name_html):
            html = self._template_env.get_template(
                self._template_name_html).render(**template_vars)
        else:
            html = None

        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(subject, 'utf-8').encode()
        msg['From'] = OPTIONS['mail_from']
        msg['To'] = ", ".join(contacts)
        msg.preamble = msg['Subject']

        # by default we are going to assume that the email is going to be text
        msg_text = MIMEText(text, 'plain', 'utf-8')
        if html:
            msg_html = MIMEText(html, 'html', 'utf-8')
            msg.attach(msg_html)

        msg.attach(msg_text)

        try:
            self._send_email_message(msg, contacts)
            LOG.debug('%s : Email sent to %s' %
                      (alert.get_id(), ','.join(contacts)))
            return (msg, contacts)
        except (socket.error, socket.herror, socket.gaierror), e:
            LOG.error('Mail server connection error: %s', e)
            return None
from email.header import Header

smtp = smtplib.SMTP(host='smtp.naver.com', port=587)

smtp.ehlo()
smtp.starttls()

smtp.login(user='******', password="")
"""
smtp.sendmail(
    '*****@*****.**', 
    '*****@*****.**',
    'hello my name is gogogogogo')
"""

unpaid_list = [
    '*****@*****.**', '*****@*****.**', '*****@*****.**'
]

for customer in unpaid_list:

    msg = MIMEText('본문입니다. 돈내라고!!')
    msg['Subject'] = Header("돈내라 안내면 짜른다.", charset="UTF-8")
    msg['From'] = '*****@*****.**'
    msg['To'] = customer

    smtp.send_message(msg)

smtp.quit()

print('main send..')
Example #8
0
def _format_addr(s):
    from email.utils import parseaddr, formataddr
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))
Example #9
0
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

host_server = 'smtp.qq.com'  #smtp
sender_qq = '*****@*****.**'
pwd = 'billbdbbcnaqbbgj'

sender_sina_mail = "*****@*****.**"
receiver = '*****@*****.**'
mail_title = '【阿里云服务器】'
mail_content = "你好,<p>这里是使用python登录qq邮箱发送HTML格式邮件的测试程序: </p><p><ahref='https://github.com/RainBowAurora'>github</a></p>"

msg = MIMEMultipart()
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_sina_mail
msg["To"] = Header("测试邮箱", 'utf-8')

msg.attach(MIMEText(mail_content, 'html', 'utf-8'))

try:
    smtp = SMTP_SSL(host_server)
    smtp.set_debuglevel(0)
    smtp.ehlo(host_server)
    smtp.login(sender_qq, pwd)
    smtp.sendmail(sender_sina_mail, receiver, msg.as_string())
    smtp.quit()
    print("邮件发送成功")
except smtplib.SMTPException:
    print("无法发送邮件")
Example #10
0
def _format_addr(self, s):
    """
    :return: Alias_name <*****@*****.**>
    """
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))
Example #11
0
from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.utils import parseaddr, formataddr
import smtplib

msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


from_addr = input('From: ')
password = input('Password: '******'To: ')
smtp_server = input('SMTP server: ')

msg = MIMEText('Hello, This message was sent by Python.\n吴远航大帅哥!!!!', 'plain',
               'utf-8')
msg['From'] = _format_addr('你的超级大粉丝Sam Du <%s>' % from_addr)
msg['To'] = _format_addr('吴远航 <%s>' % to_addr)
msg['Subject'] = Header('来自 Sam Du PyCharm的粉丝来信...', 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 465)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
Example #12
0
import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方邮件服务器设置
mail_host = 'smtp.163.com'  # smtp服务器
mail_user = '******'  # 需要登录的邮箱账号
mail_pass = '******'  # 邮箱密码或者授权码,需要开启smtp

#内容项,下面有引用
sender = '*****@*****.**'  # 发件人邮箱(mail_user = '******')
receivers = ['*****@*****.**', '*****@*****.**']  # 接收邮箱,可设置QQ邮箱或者其他邮箱
subject = 'Python SMTP 邮件发送测试'  #主题
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="https://blog.bwcxtech.com">这是我的博客</a></p>
"""

message = MIMEText(mail_msg, 'html', 'utf-8')  #内容
message['From'] = "{}".format(sender)  # 发送者
message['To'] = ",".join(receivers)  # 接收者
message['Subject'] = Header(subject, 'utf-8')  # 主题

try:
    smtpObj = smtplib.SMTP_SSL(mail_host, 465)  # 启用SSL发信, 端口一般是465
    smtpObj.login(mail_user, mail_pass)  # 登录验证
    smtpObj.sendmail(sender, receivers, message.as_string())  # 发送
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")
Example #13
0
# 发件人和收件人
sender = "*****@*****.**"
receiver = "*****@*****.**"

# 所使用的用来发送邮件的SMTP服务器
smtpServer = 'smtp.163.com'

# 发送邮箱的用户名和授权码(不是登录邮箱的密码)
username = "******"
password = "******"

mail_title = '这里是邮件的主题'
mail_body = '这里是邮件的正文'

# 创建一个实例
message = MIMEText(mail_body, 'plain', 'utf-8')  # 邮件正文
message['From'] = sender  # 邮件上显示的发件人
message['To'] = receiver  # 邮件上显示的收件人
message['Subject'] = Header(mail_title, 'utf-8')  # 邮件主题

try:
    smtp = smtplib.SMTP()  # 创建一个连接
    smtp.connect(smtpServer)  # 连接发送邮件的服务器
    smtp.login(username, password)  # 登录服务器
    smtp.sendmail(sender, receiver, message.as_string())  # 填入邮件的相关信息并发送
    print("邮件发送成功!!!")
    smtp.quit()
except smtplib.SMTPException as e:
    print("邮件发送失败!!!")
Example #14
0
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(
        (Header(name,
                'utf-8').encode(), addr))  # in case of apperance of chinese
Example #15
0
    def send_email(self, backend_name, mail):
        domain = self.config.get('domain')
        recipient = self.config.get('recipient')

        parent_message = mail.parent
        references = []
        while parent_message:
            references.append(u'<%s.%s@%s>' % (backend_name, mail.parent.full_id, domain))
            parent_message = parent_message.parent
        subject = mail.title
        sender = u'"%s" <%s@%s>' % (mail.sender.replace('"', '""') if mail.sender else '',
                                    backend_name, domain)

        # assume that .date is an UTC datetime
        date = formatdate(time.mktime(utc2local(mail.date).timetuple()), localtime=True)
        msg_id = u'<%s.%s@%s>' % (backend_name, mail.full_id, domain)

        if self.config.get('html') and mail.flags & mail.IS_HTML:
            body = mail.content
            content_type = 'html'
        else:
            if mail.flags & mail.IS_HTML:
                body = html2text(mail.content)
            else:
                body = mail.content
            content_type = 'plain'

        if body is None:
            body = ''

        if mail.signature:
            if self.config.get('html') and mail.flags & mail.IS_HTML:
                body += u'<p>-- <br />%s</p>' % mail.signature
            else:
                body += u'\n\n-- \n'
                if mail.flags & mail.IS_HTML:
                    body += html2text(mail.signature)
                else:
                    body += mail.signature

        # Header class is smart enough to try US-ASCII, then the charset we
        # provide, then fall back to UTF-8.
        header_charset = 'ISO-8859-1'

        # We must choose the body charset manually
        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        # Split real name (which is optional) and email address parts
        sender_name, sender_addr = parseaddr(sender)
        recipient_name, recipient_addr = parseaddr(recipient)

        # We must always pass Unicode strings to Header, otherwise it will
        # use RFC 2047 encoding even on plain ASCII strings.
        sender_name = str(Header(unicode(sender_name), header_charset))
        recipient_name = str(Header(unicode(recipient_name), header_charset))

        # Make sure email addresses do not contain non-ASCII characters
        sender_addr = sender_addr.encode('ascii')
        recipient_addr = recipient_addr.encode('ascii')

        # Create the message ('plain' stands for Content-Type: text/plain)
        msg = MIMEText(body.encode(body_charset), content_type, body_charset)
        msg['From'] = formataddr((sender_name, sender_addr))
        msg['To'] = formataddr((recipient_name, recipient_addr))
        msg['Subject'] = Header(unicode(subject), header_charset)
        msg['Message-Id'] = msg_id
        msg['Date'] = date
        if references:
            msg['In-Reply-To'] = references[0]
            msg['References'] = u" ".join(reversed(references))

        self.logger.info('Send mail from <%s> to <%s>' % (sender, recipient))
        if len(self.config.get('pipe')) > 0:
            p = subprocess.Popen(self.config.get('pipe'),
                                 shell=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            p.stdin.write(msg.as_string())
            p.stdin.close()
            if p.wait() != 0:
                self.logger.error('Unable to deliver mail: %s' % p.stdout.read().strip())
                return False
        else:
            # Send the message via SMTP to localhost:25
            try:
                smtp = SMTP(self.config.get('smtp'))
                smtp.sendmail(sender, recipient, msg.as_string())
            except Exception as e:
                self.logger.error('Unable to deliver mail: %s' % e)
                return False
            else:
                smtp.quit()

        return True
Example #16
0
File: mailer.py Project: ioos/ckan
def _mail_recipient(recipient_name,
                    recipient_email,
                    sender_name,
                    sender_url,
                    subject,
                    body,
                    headers={}):
    mail_from = config.get('smtp.mail_from')
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string())
        log.info("Sent email to {0}".format(recipient_email))

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Example #17
0
import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = '*****@*****.**'
receivers = ['*****@*****.**']  #接收邮件,可以设置为你的QQ邮箱或者其他邮箱

#三个参数:第一个为文本内容,第二个plain设置文本格式,第三个utf-8设置编码
message = MIMEText('Python 邮件发送测试……', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')  #发送者
message['To'] = Header("测试", 'utf-8')  #接收者

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")
Example #18
0
import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = "*****@*****.**"
host_qq = 'smtp.qq.com'
password_qq = ""
port_qq = 25
receivers = ["*****@*****.**"]

# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('python test send email.......', 'plain', 'utf-8')
message['From'] = Header('冯大师', 'utf-8')
message['To'] = Header('张天师')

subject = 'python send email'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP(host=host_qq, port=port_qq)
    smtpObj.login(user=sender, password=password_qq)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print('发送邮件成功!')
except smtplib.SMTPException as e:
    print('error:发送邮件失败!')
    print(e)
Example #19
0
#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  #设置服务器
mail_user = "******"  #用户名
mail_pass = "******"  #口令

receivers = ['*****@*****.**']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("W3Cschool教程", 'utf-8')
message['To'] = Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 465)  # 465 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(mail_user, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")
Example #20
0
def send_mail(receivers, mail_msg, attach_path):
    """
    发送邮件
    第三方 SMTP 服务, 这里使用 QQ

    Args:
        receivers: 邮件接收者,格式为['*****@*****.**', '*****@*****.**']
        mail_msg: 邮件内容,html字符串
        attach_path: 附件路径

    Return: True:发送成功,False:发送失败

    Raises:
    """

    print '*****************发送邮件*****************'

    mail_host = 'smtp.qq.com'  # 设置服务器
    mail_user = '******'  # 用户名
    mail_pass = '******'  # 口令
    mail_sender = '*****@*****.**'  # 发送者
    mail_from = 'Barry'  # 邮件的发件人
    mail_to = '测试部门'  # 邮件收件人
    mail_subject = 'TalkTok构建通知'  # 邮件标题

    # 发送纯文本
    # message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')

    # 发送html
    # message = MIMEText(mail_msg, 'html', 'utf-8')

    # 发送带附件的html
    message = MIMEMultipart()
    message.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    message['From'] = Header(mail_from, 'utf-8')
    message['To'] = Header(mail_to, 'utf-8')
    message['Subject'] = Header(mail_subject, 'utf-8')

    if attach_path:
        try:
            # 构造附件,传送apk文件
            pack = MIMEText(open(attach_path, 'rb').read(), 'base64', 'utf-8')
            pack["Content-Type"] = 'application/octet-stream'
            # 这里的filename,邮件中显示的名字
            pack[
                "Content-Disposition"] = 'attachment; filename="%s"' % os.path.basename(
                    attach_path)
            message.attach(pack)
        except Exception:
            print '附件不存在'
    else:
        print '邮件没有传送附件'

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号,非ssl验证
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(mail_sender, receivers, message.as_string())
        print("---邮件发送成功---")
        return True
    except smtplib.SMTPException as err:
        print("---邮件发送失败---")
        return False
    finally:
        smtpObj.quit()
def format_address(text):
    name, address = parseaddr(text)
    return formataddr((Header(name, 'utf-8').encode(), \
        address.encode('utf-8') if isinstance(address, unicode) else address))
Example #22
0
    def _send_encrypted_email(
        self,
        from_email: str,
        from_name: str,
        subject: str,
        message: str,
        public_key: Optional[str],
        pgp_public_key: PGPKey,
    ) -> None:
        # Sources:
        # - [ProtonMail](https://protonmail.com/support/knowledge-base/pgp-mime-pgp-inline/)
        # - [StackOverflow](https://stackoverflow.com/questions/54486279/how-to-send-gpg-encrypted-email-with-attachment-using-python?answertab=active#tab-top)

        msg = EmailMessage()
        msg.add_header(_name="Content-Type", _value="multipart/mixed")

        msg_text = MIMEText(message, _subtype="plain", _charset="utf-8")
        msg.attach(msg_text)

        if public_key:
            msg_attachment = EmailMessage()
            msg_attachment.add_header(
                _name="Content-Type",
                _value="application/pgp-keys",
                name="publickey.asc",
            )
            msg_attachment.add_header(
                _name="Content-Disposition",
                _value="attachment",
                filename="publickey.asc",
            )
            msg_attachment.set_payload(public_key)
            encoders.encode_base64(msg_attachment)
            msg.attach(msg_attachment)

        try:
            encrypted_message = pgp_public_key.encrypt(
                PGPMessage.new(msg.as_string()))
        except PGPError:
            raise RuntimeError

        pgp_msg = MIMEBase(
            _maintype="multipart",
            _subtype="encrypted",
            protocol="application/pgp-encrypted",
            charset="UTF-8",
        )

        pgp_msg["Date"] = formatdate()
        pgp_msg["From"] = formataddr((from_name, self.sender_email))
        pgp_msg["To"] = formataddr((self.to_name, self.to_email))
        pgp_msg["Reply-To"] = formataddr((from_name, from_email))
        pgp_msg["Subject"] = Header(subject, "utf-8")

        pgp_msg_part1 = EmailMessage()
        pgp_msg_part1.add_header(_name="Content-Type",
                                 _value="application/pgp-encrypted")
        pgp_msg_part1.add_header(_name="Content-Description",
                                 _value="PGP/MIME version identification")
        pgp_msg_part1.set_payload("Version: 1\n")
        pgp_msg.attach(pgp_msg_part1)

        pgp_msg_part2 = EmailMessage()
        pgp_msg_part2.add_header(
            _name="Content-Type",
            _value="application/octet-stream",
            name="encrypted.asc",
        )
        pgp_msg_part2.add_header(_name="Content-Description",
                                 _value="OpenPGP encrypted message")
        pgp_msg_part2.add_header(_name="Content-Disposition",
                                 _value="inline",
                                 filename="encrypted.asc")
        pgp_msg_part2.set_payload(str(encrypted_message))
        pgp_msg.attach(pgp_msg_part2)

        return self._send_smtp(pgp_msg)
Example #23
0
parameter1_emailAddress = sys.argv[1]
parameter2_repositoryName = sys.argv[2]
parameter3_previewUrl = sys.argv[3]

# 以下邮件代发服务器账号仅供测试
# 此处请填写成自己的邮件代发服务器配置(基于SMTP协议)
mail_host = "smtp.qq.com"
server_port = 465
mail_user = "******"
mail_pass = "******"

sender = mail_user
receivers = [parameter1_emailAddress]

emailMsg = "<center><h2>项目构建成功</h2></center><center><p><a href=\"" + parameter3_previewUrl + "\" style=\"color:red\">点击预览项目</a></p></center>"
message = MIMEText(emailMsg, 'html', 'utf-8')
message['From'] = Header("CI-服务器 <" + mail_user + ">", 'utf-8')
message['To'] = Header("<" + parameter1_emailAddress + ">", 'utf-8')
subject = "项目" + parameter2_repositoryName + "-任务构建通知"
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP_SSL()
    smtpObj.connect(mail_host, server_port)
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "Send Success\n0"
except smtplib.SMTPException:
    print "Error: Send Failed\n401"
Example #24
0
#!user/bin/env python3
#coding:utf-8

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))  #??


from_addr = input('From:')
password = input('Password:'******'To:')
smtp_server = input('SMTP server:')

msg = MIMEText('Hello, send by wendy...', 'plain', 'utf-8')
msg['From'] = _format_addr('WendyWang<%s>' % from_addr)
msg['To'] = _format_addr('收件人<%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()  #转码

server = smtplib.SMTP(smtp_server, 25)  #不同的邮箱SMTP默认的端口号(25)不同
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
Example #25
0
                        filename='hot.jpg')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来
        mime.set_payload(f.read())
        # 用Base64编码
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart
        msg.attach(mime)
    '''
    # 未指定用户别名,则客户端会自动提取邮件地址中的名称作为邮件的用户别名
    msg['From'] = _format_addr(from_addr)
    # msg['To'] = _format_addr(to_addrs)
    msg['To'] = '%s' % ','.join([_format_addr('<%s>' % to_addr)
                                 for to_addr in to_addrs])
    msg['Subject'] = Header(str(subject), 'utf-8').encode()
    msg['Date'] = formatdate()


    #=========================================================================
    # 发送邮件
    #=========================================================================
    try:
        # SMTP服务器设置(地址,端口):
        server = smtplib.SMTP_SSL(smtp_server, 465)
        # server.set_debuglevel(1)
        # 连接SMTP服务器(发件人地址, 客户端授权密码)
        server.login(from_addr, passwd)

        # 发送邮件
        server.sendmail(from_addr, to_addrs, msg.as_string())
Example #26
0
class SendEmail:
    # 设置smtplib所需的参数
    # 下面的发件人,收件人是用于邮件传输的。
    smtpserver = 'smtp.163.com'
    username = '******'
    sender = '*****@*****.**'
    # receiver='*****@*****.**'
    # 收件人为多个收件人
    receiver = ['*****@*****.**']

    # subject = 'Python email test'
    # 通过Header对象编码的文本,包含utf-8编码信息和Base64编码信息。以下中文名测试ok
    subject = 'IP地址变更'
    subject = Header(subject, 'utf-8').encode()

    # 构造邮件对象MIMEMultipart对象
    # 下面的主题,发件人,收件人,日期是显示在邮件页面上的。
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = 'meta_chen <{}>'.format(sender)
    # msg['To'] = '*****@*****.**'
    # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
    msg['To'] = ";".join(receiver)
    # msg['Date']='2012-3-16'
    config = configparser.ConfigParser()
    config.read("./conf.ini", encoding="utf-8")

    def __init__(self, password):
        self.password = password

    def mailsender(self):
        '''
        构造文字内容,2小时检测一次
        :return:
        '''
        logging.info("Start Check IP")
        checkip = GetIP()
        myip = checkip.getip()
        oldip = self.config.get('ip', 'oldip')
        if myip != oldip:
            logging.info('IP has Changed to : {} from {}'.format(myip, oldip))
            self.config.set('ip', 'oldip', str(myip))
            self.config.write(open("./conf.ini", "w"))
        else:
            logging.info("Nothing changed")
            return False

        text = 'Host Ip has Changed :{}'.format(myip)
        text_plain = MIMEText(text, 'plain', 'utf-8')
        self.msg.attach(text_plain)

        # 发送邮件
        smtp = smtplib.SMTP()
        smtp.connect('smtp.163.com')
        # 我们用set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
        smtp.set_debuglevel(1)
        smtp.login(self.username, self.password)
        smtp.sendmail(self.sender, self.receiver, self.msg.as_string())
        smtp.quit()
        return True

    def timeJob(self):
        '''
        定时检查ip
        :return:
        '''
        scheduler = BlockingScheduler()
        # 每2小时触发
        scheduler.add_job(self.mailsender, 'interval', days=1)
        scheduler.start()
Example #27
0
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))
Example #28
0
    def send_email(self, tel, data):
        try:
            logger.info('begging send')
            meg = '''
                <h1>需要手动下载的URL</h1>
            '''
            for url in data:
                sql = "select * from crawl_androeed_app_info WHERE url=\'{}\'".format(
                    url)
                recond = loop.run_until_complete(self.mysql_op.fetch_all(sql))
                logger.info(recond)
                if recond:
                    recond = recond[0]
                    decription = recond[5]
                    what_news = recond[6]
                    word = '<p>' + '<a href="' + url + '">' + url + '</a>' + '</p>'
                    word += '<p> decription:{} </p> <p> whatnews:{} </p>'.format(
                        decription, what_news)
                    meg += word
                sql = "select coverimg_path from crawl_androeed_coverimg WHERE url=\'{}\'".format(
                    url)
                recond = loop.run_until_complete(self.mysql_op.fetch_all(sql))
                logger.info(recond)
                if recond:
                    recond = recond[0][0]
                    cover_path = recond.replace(
                        '/home/feng/android_files1/',
                        'http://crawer2.tutuapp.net:8080/')
                    word = '<p> cover_path:{} </p>'.format(cover_path)
                    meg += word
                sql = "select screenshot_path from crawl_androeed_screenshots WHERE url=\'{}\'".format(
                    url)
                recond = loop.run_until_complete(
                    self.mysql_op.fetch_all(sql))[0][0]
                recond_screens = recond.split(",")
                re_reconds = []
                if recond:
                    for recond in recond_screens:
                        recond = ''.join(recond)
                        recond = recond.replace(
                            '/home/feng/android_files1/',
                            'http://crawer2.tutuapp.net:8080/')
                        re_reconds.append(recond)
                    word = '<p> screenshot_path:{} </p>'.format(
                        str(re_reconds))
                    meg += word

            self.message = MIMEText(meg, "html", "utf-8")
            self.message["Form"] = Header("需要手动下载的URL", "utf-8")
            self.message["To"] = Header(tel, "utf-8")
            self.message["Subject"] = Header("需要手动下载的URL", "utf-8")
            smtp_obj = smtplib.SMTP()
            smtp_obj.connect(self.host, 25)
            smtp_obj.login(self.user, self.password)
            smtp_obj.sendmail(self.sender, self.receivers,
                              self.message.as_string())
            print("Email send success")
            return True
        except smtplib.SMTPException:
            print("Email send error")
            return False
Example #29
0
def _format_addr(s):

    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))
Example #30
0
    print("发送附件示例")

    #邮件发送者
    sender = "*****@*****.**"

    #邮件接收地址列表
    receivers = "*****@*****.**"

    #发送内容构建
    #text表示发送内容为文本格式
    msg = MIMEMultipart()
    msg["From"] = "*****@*****.**"
    msg["To"] = receivers

    #构建邮件标题
    msg["subject"] = Header("开源优测_DeepTest", "utf-8")

    #构建邮件正文内容
    msg.attach(MIMEText("微信公众号,开源优测", "plain", "utf-8"))
    #构造附件,多个附件同理
    attach1 = MIMEText(open("iniFile.py", "rb").read(), "base64", "utf-8")
    attach1["Content-Type"] = "application/octest-stream"

    #这里filename随便写,将会在邮件中显示
    attach1["Content-Disposition"] = "attachment;filename=code.py"

    #关联附件到邮件中
    msg.attach(attach1)

    #SMTP服务
    smtpserver = "smtp.126.com"