Java的发送邮件
以下内容引用自http://wiki.jikexueyuan.com/project/java/sending-email.html:
用Java应用程序来发送一封电子邮件是足够简单的,但是开始时应该在机器上安装有JavaMail API和Java Activation Framework(JAF)。
- 可以从Java的标准企业网站上下载最新的JavaMail(1.2 版本)版本。
- 可以从Java的标准企业网站上下载最新的JAF(1.1.1 版本)版本。
下载并解压这些文件,在新创建的顶级目录中将找到许多应用程序的jar文件。需要CLASSPATH中添加mail.jar和activation.jar文件。(POM项目和Eclipse工程省略这一步)
一、发送一封简单的电子邮件
这是从机器中发送一封简单的电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendEmail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";//This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Now set the actual message
message.setText("This is actual message"); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封简单的电子邮件:
$ java SendEmail
Sent message successfully....
如果想要给多个收信者发送一封电子邮件,那么以下的方法将被用来发送给指定的多个电子邮件ID:
void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException
这是参数的描述:
- type:这将被设置为TO,CC或者BCC。这里CC表示副本,BCC表示Black Carbon Copy。例如Message.RecipientType.TO。
- addresses:这是电子邮件ID的数组。当指定电子邮件ID时,需要使用InternetAddress()。
二、发送一封HTML电子邮件
这是从机器发送一封HTML电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。
这个例子和前一个非常相似,除了在这用setContent()方法来设置第二个参数为"text/html"以指定 HTML 内容被包括在消息中的内容。
使用这个例子,可以发送任何HTML内容。
//File Name SendHTMLEmail.java import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendHTMLEmail {
public static void main(String[] args) { // Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";//This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message</h1>", "text/html"); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封 HTML 的电子邮件:
$ java SendHTMLEmail
Sent message successfully....
三、发送电子邮件中的附件
这是一个从机器中发送一封带有附件的电子邮件的例子。这里假设本地主机连接到了因特网并且能够发送一封电子邮件。
//File Name SendFileEmail.java import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*; public class SendFileEmail {
public static void main(String[] args) { // Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned
String from = "web@gmail.com"; // Assuming you are sending email from localhost
String host = "localhost";// This is SMTP Server,Ex:smtp.163.com // set email username
String user = "user"; // set email password
String password = "password"; // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password); // Get the default Session object.
Session session = Session.getDefaultInstance(properties); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field
message.setSubject("This is the Subject Line!"); // Create the message part
BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message
messageBodyPart.setText("This is message body"); // Create a multipar message
Multipart multipart = new MimeMultipart(); // Set text message part
multipart.addBodyPart(messageBodyPart); // Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart); // Send the complete message parts
message.setContent(multipart); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
//编译并运行这个程序来发送一封 HTML 电子邮件:
$ java SendFileEmail
Sent message successfully....
四、用户身份认证部分
如果为了身份认证的目的需要给电子邮件服务器提供用户ID和密码,可以像这样设置这些属性:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
电子邮件发送机制的剩余部分和上述解释的一样。
测试工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test27
Java的发送邮件的更多相关文章
- Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件
文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...
- Java程序发送邮件
之前上网有看到过别人总结的使用java程序发送邮件,于是自己下来练习,把自己学习的一些心得总结出来. 首先我们这里需要采用两个jar包: 需要的朋友可以自行上网去CSDN类似的网站上面找 顺便把自己测 ...
- java实现发送邮件工具
java实现发送邮件的功能:首先需要导入mail.jar: 然后需要写发送方法: 1.邮箱发送封装工具类: package com.wxjiameng.utils; import java.util. ...
- java mail Received fatal alert: handshake_failure java 无法发送邮件问题 java 发送qq邮件(含源码)
java 无法发送邮件问题 java 发送qq邮件 报错:java mail Received fatal alert: handshake_failure (使用ssl) javax.mail.M ...
- logback 发送邮件和自定义发送邮件;java类发送邮件
使用logback发送邮件 需求: 1.报错发邮件,定位错误位置以尽快解决:(报错发送邮件) 2.某一项重要操作完成之后发送邮件:(自定义发送邮件) 没有接触过logback,怎么办? 没办法,硬着头 ...
- JAVA代码发送邮件示例和解释
下载和上传附件.发送短信和发送邮件,都算是程序中很常用的功能,之前记录了文件的上传和下载还有发送短信,由于最近比较忙,邮件发送的功能就没有时间去弄,好在昨晚终于走通代码成功以163邮箱发送邮件到qq邮 ...
- java mail(发送邮件--163邮箱)
package com.util.mail; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderIn ...
- java mail发送邮件
最近做了自动发送邮件功能,带附件的:需要的jar包有
- 使用Java Mail发送邮件
本笔记参考自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17839983 JavaMail是SUN提供给开发人员在应用程序中实现 ...
- 简单的java mail发送邮件实例
mail.jar ,commons-email-X.X.jar ,activation.jar ,log4j.jar 这四个jar,放进项目里 下载地址 http://www.oracle.com/ ...
随机推荐
- Solidity 智能合约开发
需要专用浏览器或部署节点支持. Solidity (中文:固态,固体)是一种语法与Javascript相似的高级语言,它为Ethereum虚拟机(EVM)编译代码而设计. Solidity是静态类型的 ...
- 深度剖析 MySQL 事务隔离
概述 今天主要分享下MySQL事务隔离级别的实现原理,因为只有InnoDB支持事务,所以这里的事务隔离级别是指InnoDB下的事务隔离级别. 隔离级别 读未提交:一个事务可以读取到另一个事务未提交的修 ...
- VBA Promming入门教程——变量的使用
数据类型 VBA中的数据类型可分为两种 示例 String Sub Main Dim s as string s = "Hello" msgbox(s) End Sub Singl ...
- npm与cnpm
npm介绍 说明:npm(node package manager)是nodejs的包管理器,用于node插件管理(包括安装.卸载.管理依赖等) 使用npm安装插件:命令提示符执行npm instal ...
- execl, execlp, execle, execv, execvp - 执行某个文件
总览 (SYNOPSIS) #include <unistd.h> extern char **environ; int execl( const char *path, const ch ...
- centOS7安装 mysql-community-release-el7-5.noarch.rpm 包
一.rpm包 1.wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm(下载rpm) 2.rpm -ivh mysql ...
- [模板] Miller-Rabin 素数测试
细节挺多的.. #include<iostream> #include<cstdlib> #include<cstdio> #include<ctime> ...
- 条款6:若不想使用编译器自动生成的函数,就该明确拒绝(Explicity disallow the use of compiler-generated functions you do not want)
class uncopyable{ protected: uncopyable(){}; ...
- Django框架基础知识13-auth系统
我们昨天登录admin时创建的用户信息是存放在哪里了呢? auth系统的数据表: 从表的名称我们就能看出, auth_user,auth_group,auth_permission分别存放了用户,用户 ...
- 【HDU 6153】A Secret (KMP)
Problem Description Today is the birthday of SF,so VS gives two strings S1,S2 to SF as a present,whi ...