Java 发送邮件相关问题

使用java发送邮件

先上代码,稍后解释
	/**
	 * Send e-mail using 163 mail
	 * 
	 * @param hardInfo
	 * @throws AddressException
	 * @throws MessagingException
	 * @throws IOException
	 */
	public static void sendEmail()
			throws AddressException, MessagingException, IOException {
		Properties props = new Properties();
		props.setProperty("mail.host", "smtp.126.com"); // Set email protocol, 'cause I use 163 mail
		props.setProperty("mail.smtp.auth", "true");	// If do verification

		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("Mail Username", "Password");
			}
		};
		Session session = Session.getInstance(props, auth);

		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("EmailAddress"));
		msg.setRecipients(RecipientType.TO, "receive user");

		msg.setSubject("Mail Subject");

		MimeMultipart list = new MimeMultipart();
		MimeBodyPart part1 = new MimeBodyPart();

		part1.setContent("Mail Message body", "Code style, for example text/html;charset=utf-8"); // You should write "<br>" when you use text/html 

		list.addBodyPart(part1);
		MimeBodyPart part2 = new MimeBodyPart();
		part2.attachFile("filepathname"); // Set Attach file
		list.addBodyPart(part2); // Add attach file 
		msg.setContent(list);
		Transport transport = session.getTransport("smtp"); // Set protocol
		transport.connect("From address", "Mail authorization code ");
		transport.sendMessage(msg, msg.getAllRecipients());
	}

解释

  1. 发送基本上就是这样发送的,因为我们使用的smtp协议,网易邮箱为了保证一些方面的安全性,现在开启smtp使用协议必须要获取授权码,添加授权码的地方在倒数第二行。
  2. 邮件的内容使用字符串,如果你后面写的文本格式是 text/html 的话,如果要进行正文换行的话,需要使用html中的换行符号<br>来进行换行
  3. 在一开始一定要写上使用的邮箱协议,否则会出现连接失败
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值