javaMail发送邮件

需要的jar包

话不多说上代码:我的是163邮箱发送的所有服务地址是smtp.163.com 

注意:发件人邮箱必须以163.com结尾,收件人邮箱无要求。

用163邮箱确保pop和smtp服务开通。

登录密码是163的授权码

带附件的一个简单的小demo

package cn.mfinance.xct.mp.manage;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class EmailUtil {

	public static MimeMessage createAttachMail(Session session) throws Exception {
		MimeMessage message = new MimeMessage(session);
		// 设置邮件的基本信息
		// 发件人
		message.setFrom(new InternetAddress("发件人邮箱"));
		// 收件人
		message.setRecipient(RecipientType.TO, new InternetAddress("收件人邮箱"));
		// 邮件的标题
		message.setSubject("发送邮件测试");
		// 创建邮件正文,为了避免邮件正文中乱码的问题,需要使用charset=UTF-8指明字符编码
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("你好,这是一封测试邮件", "text/html;charset=UTF-8");

		// 创建邮件附件
		MimeBodyPart attach = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource("附件地址"));
		attach.setDataHandler(dh);
		attach.setFileName(dh.getName());

		// 创建容器描述数据关系
		MimeMultipart mp = new MimeMultipart();
		mp.addBodyPart(text);
		mp.addBodyPart(attach);
		mp.setSubType("mixed");

		message.setContent(mp);
		message.saveChanges();
		// 将创建的email写入到E盘存储
		// message.writeTo(new FileOutputStream("E://A//mail.eml"));
		// 返回生成的邮件
		return message;

	}

}

发送邮件的代码:

package cn.mfinance.xct.mp.manage;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;

/**
 * @author lcf
 *         发送邮件
 */
public class TestEmail {
	public static void main(String[] args) throws Exception {
		Properties prop = new Properties();
		prop.setProperty("mail.host", "smtp.163.com");
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");
		prop.setProperty("mail.password", "lcf163");

		// 使用JavaMail发送邮件的5个步骤
		// 1.创建session
		Session session = Session.getDefaultInstance(prop);
		// 开启session的debug模式,这样就可以看到程序发送Email的运行状态
		session.setDebug(true);
		// 2.通过session得到transport对象
		Transport ts = session.getTransport();
		// 3.使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器
		// 用户名和密码都通过验证之后才能够正常发送邮件给收件人。
		ts.connect("smtp.163.com", "发件人地址", "163邮箱的授权码");

		// 4.创建邮件
		Message message = EmailUtil.createAttachMail(session);

		// 5.发送邮件
		ts.sendMessage(message, message.getAllRecipients());

	}

}

有问题请留言

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值