使用Java代码实现发送电子邮件
第一步:添加 mail-1.5.0-b01.jar 包
下载地址:https://www.mvnjar.com/javax.mail/javax.mail-api/1.5.0-b01/detail.html
第二步:添加一个Java类,代码如下
package dm.com.mail;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SentJavaMail {
public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
//创建属性对象
Properties pro=new Properties();
//发送服务器需要身份验证
pro.put("mail.smtp.auth", "true");
//设置邮件服务器
pro.put("mail.host", "smtp.qq.com");
//发送邮件协议
pro.put("mail.transport.protocol", "smtp");
//端口号
pro.put("mail.smpt.prot", "465");
//qq邮箱需要ssl加密
pro.put("mail.smtp.socketFactory.port", "465");
pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//创建会话对象
Session se=Session.getInstance(pro);
//创建消息对象
Message me=new MimeMessage(se);
//设置邮件标题
me.setSubject("标题");
//创建存储内容与附件的对象
Multipart part=new MimeMultipart();
//文本内容
BodyPart text=new MimeBodyPart();
//设置内容,格式
text.setContent("测试内容 <a href='https://www.baidu.com'>百度一下,你就知道!</a>", "text/html;charset=utf-8");
//将内容添加到part中
part.addBodyPart(text);
//附件
BodyPart fu=new MimeBodyPart();
//数据源
DataSource ds=new FileDataSource("F:\\Java 48/HrManger.sql");
//添加附件
fu.setDataHandler(new DataHandler(ds));
//设置附件名
//fu.setFileName("HrManger.sql");
fu.setFileName(MimeUtility.encodeText("人力资源管理系统.sql"));
//把附件添加到part中
part.addBodyPart(fu);
//把part添加到消息对象中
me.setContent(part);
/* //设置邮件内容
me.setText("内容");*/
//设置发送人
me.setFrom(new InternetAddress("1547980719@qq.com"));
//设置收件人
me.setRecipient(RecipientType.TO, new InternetAddress("chaoqizhu@foxmail.com"));
//创建消息发送对象
Transport tran=se.getTransport();
//链接 发送地址 发件人 授权码
tran.connect("smtp.qq.com", "1547980719@qq.com","idtxqffowcelgfhg");
//发送消息
tran.sendMessage(me, me.getAllRecipients());
//关闭
tran.close();
System.out.println("发送成功");
}
}