Java实现邮件发送功能
程序员文章站
2023-11-03 17:57:34
import java.util.Properties; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; ... ......
import java.util.properties; import javax.mail.address; import javax.mail.messagingexception; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; public class sendemailutil { public static boolean sendmail(string emailaddress, string emailmsg) { // 谁发送(发送方) string from = ""; // 发给谁 string to = emailaddress; // 发送者的用户名和密码(邮箱登录用) final string username = ""; // 此处填写发送的邮箱名 final string password = ""; // 此处填写登录的邮箱密码 // 定义properties对象,设置环境信息 properties properties = new properties(); /* * mail.smtp.host :指定连接的邮件服务器的主机名。如:163邮箱就填写smtp.163.com * 若在本地测试的话,需要在本地安装smtp服务器 */ properties.setproperty("mail.smtp.host", "smtp.163.com"); // mail.smtp.auth:指定客户端是否要向邮件服务器提交验证 properties.setproperty("mail.smtp.auth", "true"); /* * mail.transport.protocol:指定邮件发送协议:smtp。smtp:发邮件;pop3:收邮件 * mail.store.protocol:指定邮件接收协议 */ properties.setproperty("mail.transport.protocol", "smtp"); // 获取session对象 session session = session.getinstance(properties); // 当设置为true,javamail ap就会将其运行过程和邮件服务器的交互命令信息输出到console中,用于javamail的调试 session.setdebug(true); try { // 创建邮件对象 mimemessage message = new mimemessage(session); // 设置邮件发送方 message.setfrom(new internetaddress(from)); // 设置邮件发送的主题<邮件标题> message.setsubject("邮件发送设置"); // 设置邮件发送的内容 message.setcontent(emailmsg,"text/html;charset=utf-8"); transport transport=session.gettransport(); // 连接邮件服务器,“”中填写邮件服务器主机名 transport.connect("",25, username, password); transport.sendmessage(message,new address[]{new internetaddress(to)}); transport.close(); return true; } catch (messagingexception e) { e.printstacktrace(); return false; } }