java无框架实现简单邮件上传案例
前言
要在网络上实现邮件功能,必须有专门的邮件服务器。这些邮件服务器类似与现实生活。中的邮局,他主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中,SMTP服务器地址:一般是smtp.xxx.com,比如163邮箱smtp.qq.com。电子邮箱(E-Mail地址)的获得需要在邮件服务器上进行申请。比如我们要使用QQ邮箱,就需要开通邮箱功能;
一、准备工作
使用Java发送Email十分简单,但是首先你应该准备JavaMail Api和java Activation Framework。
去Maven官网下载两个包:
mail.jar
activation.jar
二、实现原理
三、 java代码
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class Test {
//简单邮件:没有附件和图片,纯文本邮件
private static String password="这里填写你自己的邮箱授权码不会的话自己网上找找如何生成邮箱授权码";
private static String FromEmail="这里填写你自己的邮箱";
private static String ToEmail="这里填写发送发的邮件";
public static void main(String[] args) throws GeneralSecurityException, MessagingException {
//发送邮件需要获取协议的支持这三行代码基本为固定写法
Properties prop = new Properties();
prop.setProperty("mail.host","smtp.qq.com"); ;//设置qq邮件服务器
prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码
//如果你使用的为qq邮箱,还要设置ssl加密,加上下面四行代码即可基本也为固定写法
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
//使用javaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需要的环境信息的Session对象
//创建定义整个应用程序所需要的环境信息Session对象--》注意qq邮箱才有的其他不需要写
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FromEmail, password);
}
});
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮件的用户名和授权码连接上邮件服务器
ts.connect("smtp.qq.com",FromEmail, password);
//4.创建邮件
//注意需要传递参数
MimeMessage message = new MimeMessage(session);
//指明发件人
message.setFrom(new InternetAddress(FromEmail));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO,new InternetAddress(ToEmail));
//邮件的标题
message.setSubject("我爱你呀");
//邮件的内容
message.setContent("爱你爱你爱你","text/html;charset=utf-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
}
}