前言

用java实现邮件发送,smtp服务器,Blog跳转:https://gryffinbit.top/2022/08/17/%E7%94%A8java%E5%AE%9E%E7%8E%B0%E9%82%AE%E4%BB%B6%E5%8F%91%E9%80%81%EF%BC%8Csmtp%E6%9C%8D%E5%8A%A1%E5%99%A8/

smtp服务器授权

我使用的是126的smtp服务。之前有自己搭建过smtp服务器,但会有两个问题,第一是用腾讯云服务器搭建的话,25端口需要申请,而且不能发邮件,可能封禁。第二就是自己搭建的smtp服务器,发送邮件大概率会被扔进垃圾箱。

126邮箱授权

开启smtp服务

开启成功后,会获得一个授权码,后面会用到。

代码

mail_username 是开启smtp服务,并获取到授权码的126邮箱。

mail_auth_password 是开启smtp服务后,获取到的授权码

sender 填写发件人的邮箱地址


def __init__(self): 中的内容,是一些固定的邮件发送需要的参数

sendcontextmail 这个函数,可以把参数去掉,我写这个py的时候,是需要自动获取,定制发送内容。如果不需要参数,可以直接去掉。

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 第三方 SMTP 服务

class SMTP():
    def __init__(self):
        self.mail_host = 'smtp.126.com'  # 设置服务器
        self.mail_username = 'xxxxxxx@126.com'  # 用户名
        self.mail_auth_password = "xxxxxxx"  # 授权密码
        self.sender = 'xxxxxxx@xx.com'  # 发件人邮箱
        self.init()

    def init(self):
        self.sendcontextmail('test', 'test', 'admin')

    def send_mail(self, receiver, subject, context):
        """使用126邮箱的 smtp 提供邮件支持"""
        message = MIMEText(context, 'html', 'utf-8')
        message['From'] = self.sender
        message['To'] = receiver
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP(self.mail_host, 25)  # 生成smtpObj对象,使用非SSL协议端口号25
            smtpObj.login(self.mail_username, self.mail_auth_password)  # 登录邮箱
            smtpObj.sendmail(self.sender, receiver, message.as_string())          # 发送给一人
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")

    def sendcontextmail(self, username, passwd, usergroup):
        """可以自行定制邮件发送的内容"""
        self.receiver = "xxxx@xx.com"  # 收件人邮箱
        usergroup = usergroup.lower()
        context = "你的 svn 账号信息如下:</br>"
        context += "用户名:%s </br>" % username
        context += "密码:%s </br>" % passwd
        context += "属组:%s </br>" % str(usergroup)
        self.send_mail(self.receiver, "邮件主题", context)    # 邮箱发送时的object主题

if __name__ == "__main__":
   # while True:
      SMTP().init()

结果

评论