python3发送本机ip

#!/usr/bin/python3

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


def getip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('www.baidu.com', 0))
        ip = s.getsockname()[0]
    except:
        ip = "x.x.x.x"
    finally:
        s.close()
    return ip


def getsystemAndIpInfo():
    infos = ""
    ip_address = "0.0.0.0"
    sysstr = platform.system()
    if sysstr == "Windows":
        ip_address = socket.gethostbyname(socket.gethostname())
        infos = infos + "Windows @ " + ip_address
    elif sysstr == "Linux":
        ip_address = getip()
        infos = infos + "Linux @ " + ip_address
    elif sysstr == "Darwin":
        ip_address = socket.gethostbyname(socket.gethostname())
        infos = infos + "Mac @ " + ip_address
    else:
        infos = infos + "Other System @ some ip"
    return infos


def sendfunction():
    # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器
    mail_user = "1@qq.com"  # 用户名
    mail_pass = "xxxxxx"  # 口令

    sender = '1@qq.com'
    receivers = ['2@163.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText(getsystemAndIpInfo(), 'plain', 'utf-8')
    message['From'] = Header("shumei", 'utf-8')
    message['To'] = Header("wangyi")

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

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 587)  # 587  SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")


if __name__ == '__main__':
    # IP地址发送到指定邮箱
    sendfunction()
发布者:songJian   点击数:1810   发布时间:2021-01-04 02:03:59   更新时间:2021-01-04 02:03:59
正在加载评论...
相关文章