Java Mail(二):JavaMail介绍及发送一封简单邮件

       本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983,转载请注明。
       JavaMail是SUN提供给开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发类库,支持常用的邮件协议,如SMTP、POP3、IMAP,开发人员使用JavaMail编写邮件程序时,无需考虑底层的通信细节(Socket),JavaMail也提供了能够创建出各种复杂MIME格式的邮件内容的API。使用JavaMail,我们可以实现类似OutLook、FoxMail的软件。虽然JavaMail(仅支持JDK4及以上)也是Java的API之一,但是却没有直接加入到JDK中,所以我们需要另行下载。另外,JavaMail依赖JAF(JavaBeans Activation Framework),JAF在Java6之后已经合并到JDK中,而JDK5之前需要另外下载JAF的类库。下载地址如下:

       JavaMail:http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426.html#javamail-1.4.5-oth-JPR

       JavaMail spec:http://www.oracle.com/technetwork/java/javamail-1-149769.pdf

       JAF:http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#jaf-1.1.1-fcs-oth-JPR

       JavaMail下载好后,我们来看一下其主要内容:

README.txt:整体介绍JavaMail,需要看一下
docs/javadocs:The JavaMail API javadocs,需要看一下
mail.jar:包括JavaMail API和所有service providers,大部分用户只需要该jar包
lib/mailapi.jar	:只有JavaMail API
lib/imap.jar:The IMAP service provider
lib/smtp.jar:The SMTP service provider
lib/pop3.jar:The POP3 service provider
lib/dsn.jar:multipart/report DSN message support
demo:demo示例,简单了解,有需要再看
        JavaMail包含两部分内容,一部分是JavaMail API,定义了一组平台无关、独立于通讯协议的邮件程序框架,该部分称为应用级接口,也就是供我们调用的部分,另一部分是service provider,该部分使用特定的协议语言来实现第一部分定义的抽象类和接口,这些协议包括:SMTP、NNTP、POP3、IMAP,如果让JavaMail与邮件服务器通信,就需要相应的协议支持,该部分称为服务提供者接口,也就是JavaMail自身需要的协议支持。在使用JavaMail时,通常我们只需将mail.jar放在classpath下使用,它包含了JavaMail API部分和SUN自己实现的service provider部分。可能也有特殊的时候,我们应用程序中需要自己实现service provider部分,那我们只需要mailapi.jar。下面通过几个类来简单认识下JavaMail API:
javax.mail.Session:上下文环境信息,如服务器的主机名、端口号、协议名称等
javax.mail.Message:邮件模型,发送邮件和接收邮件的媒介,封装了邮件的信息,如发件人、收件人、邮件标题、邮件内容等
javax.mail.Transport:连接邮件SMTP服务器,发送邮件
javax.mail.Store:连接邮件POP3、IMAP服务器,收取邮件
       通过这些类,最终就可以实现收发邮件,一个发送邮件的简单示例:
public class JavaMailTest1 {
	public static void main(String[] args) throws MessagingException {
		Properties props = new Properties();
		// 开启debug调试
		props.setProperty("mail.debug", "true");
		// 发送服务器需要身份验证
		props.setProperty("mail.smtp.auth", "true");
		// 设置邮件服务器主机名
		props.setProperty("mail.host", "smtp.163.com");
		// 发送邮件协议名称
		props.setProperty("mail.transport.protocol", "smtp");
		
		// 设置环境信息
		Session session = Session.getInstance(props);
		
		// 创建邮件对象
		Message msg = new MimeMessage(session);
		msg.setSubject("JavaMail测试");
		// 设置邮件内容
		msg.setText("这是一封由JavaMail发送的邮件!");
		// 设置发件人
		msg.setFrom(new InternetAddress("java_mail_001@163.com"));
		
		Transport transport = session.getTransport();
		// 连接邮件服务器
		transport.connect("java_mail_001", "javamail");
		// 发送邮件
		transport.sendMessage(msg, new Address[] {new InternetAddress("java_mail_002@163.com")});
		// 关闭连接
		transport.close();
	}
}
       最终运行后,邮件发送成功。由于我们开启了debug调试,在控制台可以看到JavaMail和服务器之间的交互信息记录,可以发现,和 Java Mail(一):telnet实现发送收取邮件中telnet下的命令及服务器反馈信息基本一致。
       创建Session对象时可能需要的属性详细信息如下:
NameTypeDescription
mail.debugbooleanThe initial debug mode. Default is false.
mail.fromStringThe return email address of the current user, used by the InternetAddress methodgetLocalAddress.
mail.mime.address.strictbooleanThe MimeMessage class uses the InternetAddress method parseHeader to parse headers in messages. This property controls the strict flag passed to theparseHeader method. The default is true.
mail.hostStringThe default host name of the mail server for both Stores and Transports. Used if themail.protocol.host property isn't set.
mail.store.protocolStringSpecifies the default message access protocol. The Session methodgetStore() returns a Store object that implements this protocol. By default the first Store provider in the configuration files is returned.
mail.transport.protocolStringSpecifies the default message transport protocol. The Session methodgetTransport() returns a Transport object that implements this protocol. By default the first Transport provider in the configuration files is returned.
mail.userStringThe default user name to use when connecting to the mail server. Used if the mail.protocol.user property isn't set.
mail.protocol.classStringSpecifies the fully qualified class name of the provider for the specified protocol. Used in cases where more than one provider for a given protocol exists; this property can be used to specify which provider to use by default. The provider must still be listed in a configuration file.
mail.protocol.hostStringThe host name of the mail server for the specified protocol. Overrides the mail.host property.
mail.protocol.portintThe port number of the mail server for the specified protocol. If not specified the protocol's default port number is used.
mail.protocol.userStringThe user name to use when connecting to mail servers using the specified protocol. Overrides themail.user property. 

       更新于2014.01.06
       文中示例以及以后的示例中所用的邮箱账户均为在163申请的测试账户,分别为java_mail_001至java_mail_004,密码均为javamail。
       本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983,转载请注明。

  • 31
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 22
    评论
当需要在邮件正文中嵌入图片时,可以使用HTML格式的邮件,并在HTML中嵌入图片的URL。下面是使用JavaMail发送包含图片的HTML格式邮件的详细步骤: 1. 导入JavaMailjavax.activation库。 2. 创建一个MimeMessage对象。 3. 设置邮件的基本信息,包括发件人、收件人、主题等。 4. 创建一个Multipart对象,用于组合邮件正文和图片。 5. 创建一个HTML格式的邮件正文。 6. 创建一个MimeBodyPart对象,用于包装图片。 7. 将图片附件添加到MimeBodyPart对象中。 8. 将MimeBodyPart对象添加到Multipart对象中。 9. 将Multipart对象设置为邮件内容。 10. 发送邮件。 下面是一份示例代码,可以参考: ```java import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class SendMailWithImage { public static void main(String[] args) { // 发件人电子邮箱 String from = "[email protected]"; // 收件人电子邮箱 String to = "[email protected]"; // 指定发送邮件的主机为 smtp.qq.com String host = "smtp.qq.com"; //QQ 邮件服务器 // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); // 获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("你的QQ账号", "你的QQ邮箱授权码"); //发件人邮件用户名、密码 } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From: 头部头字段 message.setFrom(new InternetAddress(from)); // Set To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: 头部头字段 message.setSubject("包含图片的邮件"); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 消息 String messageText = "<h1>这是一封包含图片的HTML格式邮件!</h1><br/><img src=\"cid:image\">"; messageBodyPart.setContent(messageText, "text/html"); // 创建多重消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); String filename = "image.png"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); // 发送合成消息 message.setContent(multipart); // 发送消息 Transport.send(message); System.out.println("邮件发送成功!"); }catch (MessagingException mex) { mex.printStackTrace(); } } } ``` 其中,需要替换的部分有: - `[email protected]` 为发件人邮箱地址。 - `[email protected]` 为收件人邮箱地址。 - `smtp.qq.com` 为发件人邮箱SMTP服务器地址,可以根据实际情况进行修改。 - `你的QQ账号` 和 `你的QQ邮箱授权码` 分别为发件人邮箱的账号和授权码,需要替换为实际的内容。 - `image.png` 为要添加的图片文件名,需要替换为实际的图片文件名。 运行程序后,将会发送一封包含图片的HTML格式邮件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值