java 发送邮件

以下是两种邮件发送方式。
给出的例子是是发送HTML格式带附件的邮件。(普通文本格式的邮件基本上可以不关心,现在的邮件都是HTML格式的!)
如果不要发送附件,只要发送单纯的HTML邮件。只要把附件部分去掉即可



/**
*用spring mail 发送邮件,依赖jar:spring.jar,activation.jar,mail.jar
*/

public static void sendFileMail() throws MessagingException {
JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

// 设定mail server
senderImpl.setHost("smtp.126.com");
senderImpl.setUsername("yuhan0");
senderImpl.setPassword("******");
// 建立HTML邮件消息
MimeMessage mailMessage = senderImpl.createMimeMessage();
// true表示开始附件模式
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");

// 设置收件人,寄件人
messageHelper.setTo("slimes@126.com");
messageHelper.setFrom("yuhan0@126.com");
messageHelper.setSubject("测试邮件!");
// true 表示启动HTML格式的邮件
messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>", true);

FileSystemResource file1 = new FileSystemResource(new File("d:/logo.jpg"));
FileSystemResource file2 = new FileSystemResource(new File("d:/读书.txt"));
// 添加2个附件
messageHelper.addAttachment("logo.jpg", file1);

try {
//附件名有中文可能出现乱码
messageHelper.addAttachment(MimeUtility.encodeWord("读书.txt"), file2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new MessagingException();
}
// 发送邮件
senderImpl.send(mailMessage);
System.out.println("邮件发送成功.....");

}




/**
*用apache commons-email 发送邮件
*依赖jar:commons-email.jar,activation.jar,mail.jar
*/
public static void sendMutiMessage() {

MultiPartEmail email = new MultiPartEmail();
String[] multiPaths = new String[] { "D:/1.jpg", "D:/2.txt" };

List<EmailAttachment> list = new ArrayList<EmailAttachment>();
for (int j = 0; j < multiPaths.length; j++) {
EmailAttachment attachment = new EmailAttachment();
//判断当前这个文件路径是否在本地 如果是:setPath 否则 setURL;
if (multiPaths[j].indexOf("http") == -1) {
attachment.setPath(multiPaths[j]);
} else {
try {
attachment.setURL(new URL(multiPaths[j]));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Picture of John");
list.add(attachment);
}

try {
// 这里是发送服务器的名字:
email.setHostName("smtp.126.com");
// 编码集的设置
email.setCharset("utf-8");
// 收件人的邮箱
email.addTo("slimes@126.com");
// 发送人的邮箱
email.setFrom("yuhan0@126.com");
// 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
email.setAuthentication("yuhan0", "******");
email.setSubject("这是一封测试邮件");
// 要发送的信息
email.setMsg("<b><a href=\"http://www.baidu.com\">邮件测试内容</a></b>");

for (int a = 0; a < list.size(); a++) //添加多个附件
{
email.attach(list.get(a));
}
// 发送
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值