Java 发送邮件相关问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42568655/article/details/96725892

使用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. 在一开始一定要写上使用的邮箱协议,否则会出现连接失败

猜你喜欢

转载自blog.csdn.net/weixin_42568655/article/details/96725892