发送邮件

1.导入jar包

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>

2、写实体类

// 发送服务器
private String host;
// 发送主题
private String subject;
// 发送用户名
private String fromName;
// 发送密码
private String fromPassword;
// 接受的用户
private String toAddress;
// 发送内容
private String content;

3、配置文件

host=smtp.163.com
fromName=157****5505@163.com
fromPassword=*******

 

4、邮件发送

//发送html邮件
public void SendHtmlEmail(CommonEmail email) {
HtmlEmail htmlEmail = new HtmlEmail();
try {
// 设置邮件的各个参数
htmlEmail.setAuthentication(email.getFromName(), email.getFromPassword());
htmlEmail.setFrom(email.getFromName());
htmlEmail.setHostName(email.getHost());
htmlEmail.setCharset("UTF-8");
htmlEmail.setSubject(email.getSubject());
htmlEmail.setHtmlMsg(email.getContent());
htmlEmail.addTo(email.getToAddress());
htmlEmail.addCc(email.getFromName());
// 发送邮件
htmlEmail.send();
System.out.println("发送邮件成功!!");
} catch (EmailException e) {
System.out.println("邮件发送失败!!");
e.printStackTrace();
}

}

6、测试邮件发送

static {
properties = new Properties();
try {
String path = SendEmailTest.class.getClassLoader().getResource("emailConfig.properties").getPath();
File file = new File(path);
properties.load(new FileInputStream(file));
} catch (Exception e) {
System.out.println("配置文件加载失败");
}
}
public static void main(String[] args) {
CommonEmail email = new CommonEmail();
email.setFromName(properties.getProperty("fromName"));
email.setFromPassword(properties.getProperty("fromPassword"));
email.setHost(properties.getProperty("host"));
email.setSubject("第一次使用邮件发送功能");
email.setToAddress("115****630@qq.com");
email.setContent("<a href='www.baidu.com'>百度一下</a>");

CommonEmailSender sender = new CommonEmailSender();
sender.SendHtmlEmail(email);

}

 

其中遇到的问题:

      ①com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp7,C8CowACX1L3Z9n9a5uczGQ--.37216S2 1518335705,please see http://mail.163.com/help/help_spam_16.htm?ip=58.246.226.97&hostid=smtp7&time=1518335705

解决方法:邮件抄送给自己一份就可以了

发邮件报错535 Error:authentication failed解决方法

解决方法:可能有的原因:①你有授权码,所以密码是你的授权码,而不是你的密码 ②你的密码输入错误

 

转载于:https://www.cnblogs.com/df1151112630/p/8442471.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值