Linux uses mail and uses java to send mail

Table of contents

1. Install

2. Configuration

3. use

4. Use java to send mail


1. Install

yum -y install mailx sendmail

2. Configuration

#未加密的发送方式通过25端口,会被公有云封掉.
cat >>/etc/mail.rc <<EOF
set [email protected]
set smtp=smtp.163.com
set [email protected]
set smtp-auth-password=授权码
set smtp-auth=login
EOF

#加密的方式465端口
cat >>/etc/mail.rc <<EOF
set nss-config-dir=/etc/pki/nssdb/          #加密方式配置
set smtp-user-starttls                      #加密方式配置
set ssl-verify=ignore                       #加密方式配置
set [email protected]                      #配置发件人
set smtp=smtps://smtp.163.com:465            #配置使用qq邮箱发送邮件,不加密方式参考上面
set [email protected]            #邮箱名
set smtp-auth-password=授权码                #授权码
set smtp-auth=login                         #认证形式
EOF

3. use

mail -s [email protected]  [email protected] </etc/hosts

[email protected] is the sender

[email protected] is the recipient

4. Use java to send mail

package pers.wwz.oom.oomone.utils;


import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * 发送邮件
 * 需要依赖
 *         <dependency>
 *             <groupId>com.sun.mail</groupId>
 *             <artifactId>javax.mail</artifactId>
 *             <version>1.6.2</version>
 *         </dependency>
 */
public class MailUtils {

	/**
	 * 发件人
	 */
	public static final String SEND_FROM="[email protected]";

	/**
	 * 收件人
	 */
	public static final String SEND_TO="[email protected]";

	/**
	 * 抄送人
	 */
	public static final String SEND_CC="[email protected]";

	/**
	 * 邮件用户名
	 */
	public static final String MAIL_USERNAME="[email protected]";

	/**
	 * 邮件授权码(不是登录密码)
	 */
	public static final String MAIL_AUTH_PASSWORD="authPassword";

	public static void main(String[] args) throws MessagingException, IOException {
		sendSimpleMail();
		sendHtmlMail();
		sendFileMail();
		sendContentTagMail();

	}



	/**
	 * 创建session
	 * @return session
	 */
	private static Session createSession() {
		// SMTP服务器地址
		String smtp = "smtp.163.com";

		// 邮箱账号和密码(授权密码)
		String userName = MAIL_USERNAME;
		String password = MAIL_AUTH_PASSWORD;

		// SMTP服务器的连接信息
		Properties props = new Properties();
		props.put("mail.smtp.host", smtp); // SMTP主机号
		props.put("mail.smtp.port", "25"); // 主机端口号
		props.put("mail.smtp.auth", "true"); // 是否需要认证
		props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密

		// 创建Session
		// 参数1:SMTP服务器的连接信息
		// 参数2:用户认证对象(Authenticator接口的匿名实现类)
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		});

		// 开启调试模式
		session.setDebug(true);
		return session;
	}

	/**
	 * 发送邮件
	 * @throws MessagingException
	 */
	private static void sendSimpleMail() throws MessagingException {
		// 1.创建session
		Session session = createSession();

		// 2.创建邮件对象(Message抽象类的子类对象)
		MimeMessage msg = new MimeMessage(session); // 传入session
		msg.setFrom(new InternetAddress(SEND_FROM)); // 发件人
		msg.setRecipient(Message.RecipientType.TO, new InternetAddress(SEND_TO)); // 收件人
		msg.setRecipient(Message.RecipientType.CC, new InternetAddress(SEND_CC)); // 抄送人
		msg.setSubject("Simple-这是一封来自好友的邮件","utf-8"); // 标题
		msg.setText("Simple-愿世界和平!","utf-8"); // 正文

		// 3.发送
		Transport.send(msg);
	}

	/**
	 * 发送html邮件
	 * @throws MessagingException
	 */
	private static void sendHtmlMail() throws MessagingException {
		try {
			// 1.创建session
			Session session = createSession();

			// 2.创建邮件对象(Message抽象类的子类对象)
			MimeMessage msg = new MimeMessage(session); // 传入session
			msg.setFrom(new InternetAddress(SEND_FROM)); // 发件人
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(SEND_TO)); // 收件人
			msg.setRecipient(Message.RecipientType.CC, new InternetAddress(SEND_CC)); // 抄送人
			msg.setSubject("html-这是一封来自好友的邮件","utf-8"); // 标题

			// 邮件正文中包含有“html”标签(控制文本的格式)
			msg.setText("<b>世界</b>和平!","utf-8","html"); // 正文

			// 3.发送
			Transport.send(msg);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送附件邮件
	 * @throws MessagingException
	 */
	private static void sendFileMail() throws MessagingException, IOException {
		try {
			// 1.创建session
			Session session = createSession();

			// 2.创建邮件对象(Message抽象类的子类对象)
			MimeMessage msg = new MimeMessage(session); // 传入session
			msg.setFrom(new InternetAddress(SEND_FROM)); // 发件人
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(SEND_TO)); // 收件人
			msg.setRecipient(Message.RecipientType.CC, new InternetAddress(SEND_CC)); // 抄送人
			msg.setSubject("file-这是一封来自好友的邮件","utf-8"); // 标题

			// 3.邮件内容"复合"对象
			Multipart multipart = new MimeMultipart();

			// 正文
			BodyPart textPart = new MimeBodyPart();
			// 参数1:正文内容
			// 参数2:内容类型;字符编码集
			textPart.setContent("file-<b>世界</b>和平!!!", "text/html;charset=utf-8");

			// 附件
			BodyPart imagePart = new MimeBodyPart();
			imagePart.setFileName("look.jpg"); // 设置附件文件的显示名称
			// 数据处理对象(读取附件文件从本地磁盘进行读取)
			imagePart.setDataHandler(
					new DataHandler(
							new ByteArrayDataSource(
									Files.readAllBytes(Paths.get("D:\\tmp\\test.png")),
									"application/octet-stream")));

			// 添加至邮件内容
			multipart.addBodyPart(textPart); // 添加正文
			multipart.addBodyPart(imagePart); // 添加附件

			// 设置邮件内容
			msg.setContent(multipart);

			// 3.发送
			Transport.send(msg);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 发送正文嵌套标签邮件
	 * @throws MessagingException
	 */
	private static void sendContentTagMail() throws MessagingException, IOException {
		try {
			// 1.创建session
			Session session = createSession();

			// 2.创建邮件对象(Message抽象类的子类对象)
			MimeMessage msg = new MimeMessage(session); // 传入session
			msg.setFrom(new InternetAddress(SEND_FROM)); // 发件人
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(SEND_TO)); // 收件人
			msg.setRecipient(Message.RecipientType.CC, new InternetAddress(SEND_CC)); // 抄送人
			msg.setSubject("ContentTag-爱永不凋零!","utf-8");

			// 邮件正文部分
			BodyPart textBodyPart = new MimeBodyPart();
			StringBuilder body = new StringBuilder();
			body.append("ContentTag-<h1>世界和平</h1>");
			body.append("ContentTag-<img src=\"cid:jue\"/>"); // 通过内容ID引用附件图片
			textBodyPart.setContent(body.toString(), "text/html;charset=utf-8");

			// 邮件附件部分
			BodyPart imageBodyPart = new MimeBodyPart();
			imageBodyPart.setFileName("son.jpg"); // 读取名称
			imageBodyPart.setDataHandler( // 读取附件内容
					new DataHandler(
							new ByteArrayDataSource(
									Files.readAllBytes(Paths.get("D:\\tmp\\test.png")),
									"application/octet-stream")));
			imageBodyPart.setHeader("Content-ID", "<jue>");

			// 组合正文+附件
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(textBodyPart); // 添加正文部分
			multipart.addBodyPart(imageBodyPart); // 添加附件部分

			// 设置邮件内容
			msg.setContent(multipart);

			// 3.发送
			Transport.send(msg);

		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}



}

Reference: Sending emails with Java——Java Email_java Sending emails_Xiao Zhao's blog without hair loss

Reference: https://www.cnblogs.com/roak/p/16261702.html

Guess you like

Origin blog.csdn.net/wangwenzhe222/article/details/130282290