用javaMail发送邮件

Posted 未夏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用javaMail发送邮件相关的知识,希望对你有一定的参考价值。

电子邮件协议

SMTP是推协议,负责用户代理向邮件服务器或邮件服务器与邮件服务器间发送邮件;POP3、IMAP是拉协议,负责用户代理从邮件服务器读取邮件。

如何写一封邮件

javaMail用Message对象表示一封邮件。Message类是一个抽象类,我们通常使用它的子类MimeMessage表示一封邮件。

MimeMessage构造器接受一个Session对象,Session对象表示一个会话,该对象由Session.getInstance(property)方法生成,property参数是一个Properties对象,我们借用它设置邮件传输的相关信息。

文本邮件

package com.weixia.SMTP;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.FileOutputStream;

public class Message_text {
    public static void main(String[] args) throws Exception {
        String from = "";   // 发件人
        String to   = "";   // 收件人
        String subject = "This ia a SMTP test mail";    // 主题
        String body = "Hello,world!";   // 邮件正文
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
        
        message.setFrom(new InternetAddress(from));
        // Message.RecipientType.TO :收件人;Message.RecipientType.CC :抄送人;Message.RecipientType.BCC :密送人
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());
        message.setSubject(subject,"UTF-8");
        message.setText(body,"UTF-8");
        message.saveChanges();
        message.writeTo(new FileOutputStream("F:\\\\mail.eml"));
    }
}

InternetAddress类解析邮件地址,它的构造器接受一个邮箱格式的字符串,放回一个InternetAddress对象;它的parse方法作用相同,但返回InternetAddress[],可以用来群发。

html格式邮件

package com.weixia.SMTP;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.FileOutputStream;

public class MailWithHtml {
    public static void main(String[] args) throws Exception {
        String from = "";
        String to   = "";
        String subject = "This ia a SMTP test mail";
        String body = "<p>Hello,world!</p>";
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
        
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());
        message.setSubject(subject,"UTF-8");
        message.setContent(body,"text/html;charset=UTF-8");
        message.saveChanges();
        message.writeTo(new FileOutputStream("F:\\\\mailWithHtml.eml"));
    }
}

HTML格式只需改变设置正文的方法,指明MIME类型。

含有图片、附件或其他媒体类型的邮件

这种复杂邮件,我们把图片、附件或其他媒体类型看作是一个BodyPart对象。因为Message对象setContent方法接受Multipart类型参数,所以必须把BodyPart封装为Multipart对象。

封装的方法如下图:

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class MultiMail {
	public static void main(String[] args) throws Exception {
		String from = "";
        String to   = "";
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		message.setSubject("这是我用java发送的一封邮件", "UTF-8");
		message.setSentDate(new Date());
		
		// create picture node
		MimeBodyPart image = new MimeBodyPart();
		FileDataSource file = new FileDataSource("F:\\\\邮件.jpg");
		image.setDataHandler(new DataHandler(file));
		// 后边引用该ID时,须使用"cid:idName"的形式,例如"<img src=\'cid:image_id\' />"
		image.setContentID("image_id");
		
		// create text node
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("<p>This is a test picture</p><img src=\'cid:image_id\' />","text/html;charset=UTF-8");
		
		MimeMultipart text_image = new MimeMultipart("related");
		text_image.addBodyPart(image);
		text_image.addBodyPart(text);
		// 为了添加附件,将text_image封装为BodyPart对象
		MimeBodyPart text_image_node = new MimeBodyPart();
		text_image_node.setContent(text_image);
		
		// 创建附件
		MimeBodyPart attachment = new MimeBodyPart();
		FileDataSource attachmentFile = new FileDataSource("F:\\\\mail.eml");
		DataHandler handler = new DataHandler(attachmentFile);
		attachment.setDataHandler(handler);
		attachment.setFileName(attachmentFile.getName());
		
		MimeMultipart body = new MimeMultipart("mixed");
		body.addBodyPart(text_image_node);
		body.addBodyPart(attachment);
		
		message.setContent(body);
		message.saveChanges();
		
		return message;
	}
}

发送邮件

在发送邮件时,我们要设置传输邮件的相关信息,这里我们使用Properties对象来设置Session会话对象。

通过Session对象获取Transport对象,用connect方法连接邮件服务器,然后用sendMessage方法发送邮件。

SSL连接

现在邮件服务提供商通常使用SSL加密连接,设置SSL如下:

String smtpPort = "465";
Properties property = new Properties();
property.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
property.setProperty("mail.smtp.socketFactory.fallback","false");
property.setProperty("mail.smtp.socketFactory.port",smtpPort);

完整代码如下:

package com.weixia.SMTP;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class SentMultiMail {
	public static void main(String[] args) throws Exception {
		String emailAccount = "";
		String emailPassword = "";
		
		String recipient = "";
		
		String smtpHost = "smtp.sina.com";
		String smtpPort = "465";
		
		Properties property = new Properties();
		
		property.setProperty("mail.transport.protocol","smtp");
		property.setProperty("mail.smtp.host",smtpHost);
		property.setProperty("mail.smtp,port",smtpPort);
		property.setProperty("mail.smtp.auth","true");
		
		property.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		property.setProperty("mail.smtp.socketFactory.fallback","false");
		property.setProperty("mail.smtp.socketFactory.port",smtpPort);
		
		Session session = Session.getInstance(property);
		session.setDebug(true);
		MimeMessage message = createMail(session, emailAccount, recipient);
		
		Transport transport = session.getTransport();
		transport.connect(emailAccount, emailPassword);
		transport.sendMessage(message,message.getAllRecipients());
		transport.close();
	}
	
	public static MimeMessage createMail(Session session, String from, String to) throws Exception {
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		message.setSubject("这是我用java发送的一封邮件", "UTF-8");
		message.setSentDate(new Date());
		
		// create picture node
		MimeBodyPart image = new MimeBodyPart();
		FileDataSource file = new FileDataSource("F:\\\\邮件.jpg");
		image.setDataHandler(new DataHandler(file));
		// 后边引用该ID时,须使用"cid:idName"的形式,例如"<img src=\'cid:image_id\' />"
		image.setContentID("image_id");
		
		// create text node
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("<p>This is a test picture</p><img src=\'cid:image_id\' />","text/html;charset=UTF-8");
		
		MimeMultipart text_image = new MimeMultipart("related");
		text_image.addBodyPart(image);
		text_image.addBodyPart(text);
		// 为了添加附件,将text_image封装为BodyPart对象
		MimeBodyPart text_image_node = new MimeBodyPart();
		text_image_node.setContent(text_image);
		
		// 创建附件
		MimeBodyPart attachment = new MimeBodyPart();
		FileDataSource attachmentFile = new FileDataSource("F:\\\\mail.eml");
		DataHandler handler = new DataHandler(attachmentFile);
		attachment.setDataHandler(handler);
		attachment.setFileName(attachmentFile.getName());
		
		MimeMultipart body = new MimeMultipart("mixed");
		body.addBodyPart(text_image_node);
		body.addBodyPart(attachment);
		
		message.setContent(body);
		message.saveChanges();
		
		return message;
	}
}

参考链接

JavaMail入门第二篇 创建邮件

基于JavaMail的Java邮件发送:简单邮件发送

以上是关于用javaMail发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

javamail 发送邮件(SSL)

邮件实现详解------JavaMail 发送(带图片和附件)和接收邮件

javamail发送邮件(转)

Android Java使用JavaMail API发送和接收邮件的代码示例

工具类-发送邮件(通过JavaMail发送)

JavaMail直接发送邮件