一、代码功能
Java实现发送邮件功能,使用mail包里面的函数进行实现此功能。话不多说,直接贴代码。
二、功能实现
邮件实体
package com.sjsq.entity; /** * 邮件实体类 */ public class Email { // 主题 private String subject; // 内容 private String conetent; public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getConetent() { return conetent; } public void setConetent(String conetent) { this.conetent = conetent; } }
邮件参数配置
package com.sjsq.properties; /** * 邮件参数配置 */ public class MailProperties { // 发件人 public static final String FROM = ""; // 发件主机 public static final String HOST = ""; // 发件人账号 public static final String USERNAME = ""; // 发件人密码 public static final String PASSWORD = ""; }
发送邮件
package com.sjsq.util; import com.sjsq.entity.Email; import com.sjsq.properties.MailProperties; import javax.mail.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * 发送邮件 */ public class SendMail { // 发送邮件 public static void sendMail(Email email,String address){ // 定义收件人 InternetAddress to_address[] = new InternetAddress[1]; try { to_address[0] = new InternetAddress(address); } catch (AddressException e) { e.printStackTrace(); } // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", MailProperties.HOST); properties.put("mail.smtp.auth", "true"); // 获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(MailProperties.USERNAME,MailProperties.PASSWORD); } }); // 定义头部字段及发邮件 try { // 创建默认的MimeMessage对象 MimeMessage message = new MimeMessage(session); // 设置发件人From 头部字段 message.setFrom(new InternetAddress(MailProperties.FROM)); // 设置收件人To 头部字段 message.addRecipients(Message.RecipientType.TO,to_address); // 设置Subject 头部字段 message.setSubject(email.getSubject()); // 设置消息体 message.setText(email.getConetent()); // 发送消息 Transport.send(message); System.out.println("发送成功"); } catch (MessagingException e) { e.printStackTrace(); } } }
主函数
package com.sjsq.main; import com.sjsq.entity.Email; import static com.sjsq.util.SendMail.sendMail; /** * 主函数 */ public class Main { // 测试 public static void main(String[] args) { String subject = "Java测试邮件"; String concent = "测试内容!"; String address = "helongqiang@qq.com"; Email email = new Email(); email.setSubject(subject); email.setConetent(concent); sendMail(email,address); } }
三、源码下载
Java实现发送邮件功能
Java实现发送邮件功能,代码经多次测试运行无误,请放心下载!更多下载资源、学习资料请访问CSDN下载频道.
https://download.csdn.net/download/helongqiang/79841043
点赞的早日脱单暴富,走上人生巅峰!!!