提供两个发送短信和发送邮件的工具类,开箱即用

        前言:现在基本都是SpringBoot开发项目,所以要先在yml文件配置一些密钥之类的;

email:
  emailFrom: 22**5@qq.com
  host: smtp.**com
  authorizationCode: *******
  emailContent:
  emailTo: lwd****06@163.com

sendSMS:
  signName: **
  endpoint: ******
  templateCode: *****
  accessKeyId: ***********
  accessKeySecret: ******************

一.发送短信SMSUtil

@Slf4j
@Component
public class SMSUtil {

    @Value("${sendSMS.accessKeyId}")
    private String accessKeyId;

    @Value("${sendSMS.accessKeySecret}")
    private String accessKeySecret;

    @Value("${sendSMS.signName}")
    private String signName;

    @Value("${sendSMS.templateCode}")
    private String templateCode;

    @Value("${sendSMS.endpoint}")
    private String endpoint;

    public SendSmsResponse sendSMS(String phoneNumber, String code) throws Exception {

        com.aliyun.dysmsapi20170525.Client client = createClient(accessKeyId, accessKeySecret);

        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);
        code = new JSONObject(map).toString();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(code);
        return client.sendSms(sendSmsRequest);
    }

    public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint; // 域名
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

}

二.发送邮箱MailUtil

@Slf4j
@Component
public class MailUtil {

    @Value("${email.emailFrom}")
    String emailFrom;

    @Value("${email.host}")
    String host;

    @Value("${email.authorizationCode}")
    String authorizationCode;

    @Value("${email.emailContent}")
    String emailContent;

    @Value("${email.emailTo}")
    String emailTo;

    public void sendNoticeEmails(String description) throws Exception {

        // 1.创建连接对象javax.mail.Session
        // 2.创建邮件对象 javax.mail.Message
        // 3.发送一封激活邮件
        String from = emailFrom;// 发件人电子邮箱

        Properties properties = System.getProperties();// 获取系统属性
        properties.setProperty("mail.smtp.host", host);// 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
        properties.setProperty("mail.smtp.auth", "true");// 打开认证


        //QQ邮箱需要下面这段代码,163邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);


        // 1.获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailFrom, authorizationCode); // 发件人邮箱账号、授权码
            }
        });

        // 2.创建邮件对象
        Message message = new MimeMessage(session);
        // 2.1设置发件人
        message.setFrom(new InternetAddress(from));
        // 2.2设置接收人
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
        // 2.3设置邮件主题
        message.setSubject("系统异常通知");
        // 2.4设置邮件内容
        String content = "<html><head></head><body><h1>系统发生异常通知,请前往后台处理</h1><h3>通知信息为:" + description + "</h3></body></html>";
        message.setContent(content, "text/html;charset=UTF-8");
        // 3.发送邮件
        Transport.send(message);
    }
    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是一个简单的邮件工具类的例子: ``` import smtplib from email.mime.text import MIMEText class Mailer: def __init__(self, host, port, username, password): self.host = host self.port = port self.username = username self.password = password def send(self, to, subject, message): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = self.username msg['To'] = to with smtplib.SMTP(self.host, self.port) as smtp: smtp.login(self.username, self.password) smtp.send_message(msg) mailer = Mailer('smtp.example.com', 587, 'user@example.com', 'password') mailer.send('recipient@example.com', 'Subject', 'Message') ``` 这个类提供了一个 `send` 方法,可以用来发送邮件。在构造函数中,你需要提供 SMTP 服务器的地址、端口、用户名和密码。然后,你就可以使用 `send` 方法发送邮件了。 如果你想实现邮件接收功能,你可以使用 Python 的 `imaplib` 库。下面是一个例子: ``` import imaplib class MailReceiver: def __init__(self, host, port, username, password): self.host = host self.port = port self.username = username self.password = password def receive(self): with imaplib.IMAP4(self.host, self.port) as imap: imap.login(self.username, self.password) imap.select() _, messages = imap.search(None, 'ALL') for message in messages[0].split(): _, msg = imap.fetch(message, '(RFC822)') yield msg[0][1] receiver = MailReceiver('imap.example.com', 993, 'user@example.com', 'password') for message in receiver.receive(): print(message) ``` 这个类提供了一个 `receive` 方法,可以用来接收邮件。像发送邮 ### 回答2: 实现一个邮件工具类,可以本地邮件发送和邮件接受功能。 邮件工具类的主要功能是通过使用JavaMail API来发送和接收电子邮件。下面是实现这个功能的步骤: 1. 首先,我们需要导入JavaMail API的相关依赖。可以从Maven仓库中下载并添加到项目中。 2. 创建一个邮件发送方法sendEmail,该方法接受收件人地址、主题、正文和附件等参数。在该方法中,我们可以使用JavaMail API中的SMTP协议来发送邮件。具体步骤如下: a. 创建一个Properties对象,用于设置邮件服务器的相关配置。设置SMTP服务器地址、端口号和身份验证等参数。 b. 创建一个Session对象,用于与邮件服务器进行通信。 c. 创建一个MimeMessage对象,用于表示一封邮件。设置发件人、收件人、主题和正文等内容。 d. 如果需要发送附件,则通过MimeMultipart对象添加附件内容。 e. 使用Transport类的send方法将邮件发送到指定的收件人地址。 3. 创建一个邮件接收方法receiveEmail,该方法接受收件人地址和邮件服务器的相关配置参数。在该方法中,我们可以使用JavaMail API中的POP3协议来接收邮件。具体步骤如下: a. 创建一个Properties对象,用于设置邮件服务器的相关配置。设置POP3服务器地址、端口号和身份验证等参数。 b. 创建一个Session对象,用于与邮件服务器进行通信。 c. 使用getStore方法获取存储邮件的Folder对象。 d. 使用Folder类的open方法打开文件夹,并通过getMessage方法获取邮件。 e. 遍历获取的邮件,获取发件人、主题、正文和附件等内容。 通过以上步骤,我们可以实现一个简单的邮件工具类,可以用于本地邮件发送和接收功能。当然,还有其他更复杂的功能和安全性设置可以在实践中进行进一步扩展和完善。 ### 回答3: 实现一个邮件工具类,可以本地邮件发送和邮件接收功能的步骤如下: 1. 导入相关的库和模块,如smtplib和imaplib等,以便进行邮件发送和接收的操作。 2. 创建一个邮件工具类,定义发送邮件和接收邮件的方法。 3. 在发送邮件的方法中,设置邮件的发送者、接收者、主题、正文等信息。使用SMTP服务器进行邮件发送。 4. 在接收邮件的方法中,连接到IMAP服务器,登录邮箱账号,选择邮箱文件夹,如收件箱。 5. 根据需求,可以添加邮件的过滤条件,如按发件人、主题、日期等进行过滤。 6. 遍历收件箱中的邮件,获取邮件的主题、发件人、日期等信息,并可以进行相应的处理,如打印、保存附件等。 7. 关闭IMAP服务器的连接。 8. 最后,测试邮件发送和接收的功能是否正常,可调用邮件工具类发送和接收方法,传入相应的参数,观察是否能成功发送和接收邮件。 需要注意的是,实现邮件发送和接收功能需要配置正确的SMTP和IMAP服务器地址、端口号、邮箱账号和密码等信息。同时,还需要根据自己的需求,对邮件的内容、格式、附件等进行相应的处理和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值