JavaMail邮件的发送

来源:互联网 发布:淘宝营业执照代办 编辑:程序博客网 时间:2024/04/28 02:35
package star.july.mail;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Message.RecipientType;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;//JavaMail发送邮件public class JavaMail {public static void main(String[] args) throws Exception, Exception {//1、创建链接并登录服务器/** * 参数一:连接服务器的主机地址和登陆配置 * 参数二:指定用户名和密码(需要验证登陆的(加密的)) */Properties prop = new Properties();prop.setProperty("mail.host", "smtp.sina.com");//邮箱服务器,端口默认25prop.setProperty("mail.smtp.auth", "true");  //是否需要验证登录//创建一个Authenticator的子类对象Authenticator auth = new Authenticator(){@Overrideprotected PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication("ericxu12345@sina.com", "eric12345");}};//Authenticator:用于对用户名和密码进行加密Session session = Session.getDefaultInstance(prop,auth);//打开发送的debug模式:看到发送邮件的全过程session.setDebug(true);System.out.println(session);//2、创建一封邮件(指定发件人,收件人,主题,内容)MimeMessage mail = new MimeMessage(session);//2.1、指定发件人(和登陆用户一致)mail.setFrom(new InternetAddress("ericxu12345@sina.com"));//2.2 指定收件人//参数一:收件类型 TO:收件人 CC:抄送人 BCC:密抄送人mail.setRecipient(RecipientType.TO,new InternetAddress("jackyun12345@sina.com"));//2.3 主题mail.setSubject("这是一封javamail发送的测试邮件");//2.4 内容mail.setContent("测试内容:七夕快乐!","text/plain;charset=utf-8");//3 发送邮件Transport.send(mail);}}

0 0
原创粉丝点击