Jmail发送邮件工具类分享
程序员文章站
2023-12-19 22:29:10
好久没更新博客了,实在是拖延症严重啊,好可怕,先更新个工具类吧,之前写的发送邮件的小工具,话不多说上代码
import lombok.extern...
好久没更新博客了,实在是拖延症严重啊,好可怕,先更新个工具类吧,之前写的发送邮件的小工具,话不多说上代码
import lombok.extern.slf4j.slf4j; import java.util.properties; import javax.mail.*; import javax.mail.internet.addressexception; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; /** * <b>发送邮件工具类</b><br/> * <b>create on:</b>2016/10/9 16:14<br/> * * @author : liud<br/> */ @slf4j public class sendmailutil { /** * 发送邮件 * @param smtphost * @param fromuser * @param fromuserpassword * @param emailport * @param touser * @param subject * @param messagetext */ public static boolean dosendemail(string smtphost, final string fromuser, final string fromuserpassword, string username, string emailport, string touser, string subject, string messagetext) throws exception { boolean flag = false; try { properties props = new properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", emailport); props.put("mail.smtp.auth", "true"); session session = session.getdefaultinstance(props, new authenticator(){ protected passwordauthentication getpasswordauthentication() { return new passwordauthentication(fromuser, fromuserpassword); }}); mimemessage message = new mimemessage(session); // 发件人 internetaddress from = new internetaddress(fromuser); message.setfrom(from); // 收件人 internetaddress to = new internetaddress(touser); message.setrecipient(message.recipienttype.to, to); // 邮件标题 message.setsubject(subject); // 邮件内容,也可以使纯文本"text/plain" message.setcontent(messagetext, "text/html;charset=gbk"); message.savechanges(); transport transport = session.gettransport("smtp"); // smtp验证,就是你用来发邮件的邮箱用户名密码 transport.connect(smtphost, username, fromuserpassword); // 发送 transport.sendmessage(message, message.getallrecipients()); transport.close(); flag = true; } catch (addressexception e) { log.error("地址异常:{}", e); throw e; } catch (messagingexception e) { log.error("消息异常:{}", e); throw e; } catch (exception e) { log.error("系统异常:{}", e); throw e; } return flag; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。