Java发邮件
准备工作
- 自己创建一个邮箱用于发送邮件(推荐使用网易163邮箱,QQ邮箱发送可能会失败),并且确保发送邮件的邮箱已经打开了smtp和pop3功能
实例
- 手动发邮箱(注意:发送邮件的账号和密码必须是用Base64加密过的)
- 可在之前用telnet测试一下
ehlo<Space>主机名<CRLF>
SMTP 邮件发送程序与SMTP邮件接收程序建立连接的第一条必须的命令,主机名是当前邮件发送者的主机名;
auth<Space>login<CRLF>
现在一般的邮箱都需要进行用户名、密码验证,而且SMTP 邮件服务器一般都使用 Login 验证方式,因此就不用考虑其他两种验证方式了;
mail<Space>from:发送人邮箱地址<CRLF>
从命令中很明显地看出来 mail 命令用于指定邮件发送者的邮箱地址;
rcpt<Space>to:收件人邮箱地址<CRLF>
同理,rcpt 命令用于指定邮件接收人的邮箱地址;
data<CRLF>
data 命令用于表示该命令之后的所有内容、数据都将被作为邮件的相关内容,直到遇到<CRLF>.<CRLF>标识符,即一个句号“.”结束邮件的发送内容;
quit<CRLF>
该命令结束邮件发送过程,关闭本机与SMTP 邮件服务器的网络连接。
publicclassSendMail {
publicstaticvoidmain(String[] args) throws IOException {
Socket socket = new Socket("smtp.qq.com",25);
OutputStream out = socket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
out.write("ehlo flx\r\n".getBytes());
System.out.println(in.readLine());
System.out.println(in.readLine());
System.out.println(in.readLine());
out.write("auth login\r\n".getBytes());
System.out.println(in.readLine());
out.write("MTE2NDA3NzYxMQ==\r\n".getBytes());
System.out.println(in.readLine());
out.write("Y3N4MTM3ODY1NjQ4MDg=\r\n".getBytes());
System.out.println(in.readLine());
out.write("mail from:<1164077611@qq.com>\r\n".getBytes());
System.out.println(in.readLine());
out.write("rcpt to:<18569230103@163.com>\r\n".getBytes());
System.out.println(in.readLine());
out.write("data\r\n".getBytes());
System.out.println(in.readLine());
out.write("aaaaaaaaaaaaaaa\r\n".getBytes());
out.write(".\r\n".getBytes());
System.out.println(in.readLine());
}
}
- JavaMail开发,先引入jar文件:
- activation.jar
- mail.jar
publicclassMail2 {
// 邮件发送参数信息static Properties prop = new Properties();
static String user = "itcast";
static String pwd = "888";
// 初始化参数static {
// 协议
prop.put("mail.transport.protocol", "smtp");
// 端口
prop.put("mail.smtp.port", "25");
// 主机
prop.put("mail.smtp.host", "localhost");
// 认证
prop.put("mail.smtp.auth", "true");
// 调试
prop.put("mail.debug", "true");
}
//1. 发送邮件publicstaticvoidsendEmail() throws Exception {
//创建会话对象
Session session = Session.getDefaultInstance(prop, new MyAuthenticator(user,pwd));
//邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("itcast@it.com"));
message.setRecipient(RecipientType.CC, new InternetAddress("yuanjie@it.com"));
message.setSentDate(new Date());
message.setSubject("踢足球..............");
message.setText("那些人去???");
message.saveChanges();
// 发送
Transport.send(message);
}
//2. 发送html邮件publicstaticvoidsendHtmlEmail() throws Exception {
//创建会话对象
Session session = Session.getDefaultInstance(prop, new MyAuthenticator(user,pwd));
//邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("itcast@it.com"));
message.setRecipient(RecipientType.CC, new InternetAddress("yuanjie@it.com"));
message.setSentDate(new Date());
message.setSubject("踢足球..............");
message.setContent("<a href='http://www.baidu.com'>度娘</a>", "text/html;charset=GBK");
message.saveChanges();
// 发送
Transport.send(message);
}
//3. 发送html + img 邮件publicstaticvoidsendHtmlAndImgEmail() throws Exception {
// 会话对象
Session session = Session.getDefaultInstance(prop, new MyAuthenticator(user, pwd));
// 邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("itcast@it.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("yuanjie@it.com"));
message.setSubject("图片");
message.setSentDate(new Date());
// 设置多功能邮件
MimeMultipart multipart = new MimeMultipart("related");
message.setContent(multipart);
// 邮件内容: html + 文本
MimeBodyPart body = new MimeBodyPart();
// 邮件“内嵌资源”
MimeBodyPart source = new MimeBodyPart();
// 添加邮件内容,到多功能用途邮件
multipart.addBodyPart(body);
multipart.addBodyPart(source);
// 设置资源
DataSource ds = new FileDataSource(Mail2.class.getResource("1.jpg").getPath());
DataHandler handler = new DataHandler(ds);
source.setDataHandler(handler);
// 设置资源id,供邮件内容引用
source.setContentID("1.jpg");
// 设置内容
body.setContent("<img src='cid:1.jpg' />好好好", "text/html;charset=UTF-8");
// 保存邮件、发送
message.saveChanges();
Transport.send(message);
}
//4. 发送html + img + 附件邮件publicstaticvoidsendHtmlWithImgAndAttacheEmail() throws Exception {
// 会话对象
Session session = Session.getDefaultInstance(prop, new MyAuthenticator(user, pwd));
// 邮件对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("itcast@it.com"));
message.setRecipient(RecipientType.TO, new InternetAddress("yuanjie@it.com"));
message.setSubject("图片");
message.setSentDate(new Date());
/*********设置总邮件块***********/
MimeMultipart mix = new MimeMultipart("mixed");
message.setContent(mix);
// 左右快
MimeBodyPart left = new MimeBodyPart();
MimeBodyPart right = new MimeBodyPart();
// 添加
mix.addBodyPart(left);
mix.addBodyPart(right);
// 设置右边: 附件(中文:1. 路径解码; 2. 通过setFileName设置文件编码为gbk)
DataSource fileDs = new FileDataSource(URLDecoder.decode(Mail2.class.getResource("用户须知.doc").getPath(), "UTF-8"));
DataHandler fileHandler = new DataHandler(fileDs);
right.setDataHandler(fileHandler);
// 设置文件
right.setFileName(MimeUtility.encodeText("用户须知.doc"));
// 设置多功能邮件
MimeMultipart multipart = new MimeMultipart("related");
// 设置左边块: html + 文本 + 资源
left.setContent(multipart);
// 邮件内容: html + 文本
MimeBodyPart body = new MimeBodyPart();
// 邮件“内嵌资源”
MimeBodyPart source = new MimeBodyPart();
// 添加邮件内容,到多功能用途邮件
multipart.addBodyPart(body);
multipart.addBodyPart(source);
// 设置资源
DataSource ds = new FileDataSource(Mail2.class.getResource("1.jpg").getPath());
DataHandler handler = new DataHandler(ds);
source.setDataHandler(handler);
// 设置资源id,供邮件内容引用
source.setContentID("1.jpg");
// 设置内容
body.setContent("<img src='cid:1.jpg' />好好好", "text/html;charset=UTF-8");
// 保存邮件、发送
message.saveChanges();
Transport.send(message);
}
// 认证staticclassMyAuthenticatorextendsAuthenticator{
private String user;
private String pwd;
publicMyAuthenticator(String user, String pwd) {
super();
this.user = user;
this.pwd = pwd;
}
publicMyAuthenticator() {}
protected PasswordAuthentication getPasswordAuthentication() {
returnnew PasswordAuthentication(user, pwd);
}
}
publicstaticvoidmain(String[] args) throws Exception {
// sendEmail();// sendHtmlEmail();// sendHtmlAndImgEmail();
sendHtmlWithImgAndAttacheEmail();
}
}