Java实现邮件发送

实现步骤:


第一步 编写邮件身份验证类
用来验证SMTP服务器身份。程序继承了Authenticator类,它主要用来实现登录邮件服务器时的认证。它包含两个属性:username和password,分别用来存储认证时所需的用户名和密码信息。程序重写了Authenticator类的getPasswordAuthentication()方法,该方法返回PasswordAuthentication对象,此对象包含通过STMP服务器身份验证所需的用户名和密码,供认证时session调用。

import java.util.Properties;  
import javax.mail.Authenticator;  
import javax.mail.PasswordAuthentication;  
  
public class Auth extends Authenticator {  
  
    private String username = "";  
    private String password = "";  
  
    public Auth(String username, String password) {  
        this.username = username;  
        this.password = password;  
    }  
    public PasswordAuthentication getPasswordAuthentication() {  
        return new PasswordAuthentication(username, password);  
    }   
} 

第二步 编写发送邮件类
代码说明:该程序为一个邮件发送通用类的程序,SendMail构造方法实现对发送邮件身份的认证,获得Session对象。该方法中SMTPHost、Port、MailUsername、MailPassword分别表示所使用的SMTP服务器、服务器的smtp端口、用户名和密码。sendingMimeMail()方法为发送邮件的方法,在该方法需要传入的参数中,MailFrom为发件人电子信箱,MailTo为收件人电子信箱,MailCopyTo为抄送人电子信箱,MailBCopyTo为暗送人电子信箱,MailSubject为发送邮件主题,MailBody为发送邮件正文。sendingMimeMail()返回boolean类型,表示是否发送成功。发送邮件时先调用构造方法SendMail()创建邮件发送对象,然后调用sendingMimeMail()方法发送。

import java.util.Properties;  
import javax.mail.Message;  
import javax.mail.Session;  
import javax.mail.Transport;  
import javax.mail.internet.InternetAddress;  
import javax.mail.internet.MimeMessage;  
  
public class SendMail {  
  
    private Properties props;// 系统属性  
    private Session mailSession;// 邮件会话对象  
    private MimeMessage mimeMsg; // MIME邮件对象  
  
  
    public SendMail(String SMTPHost, String Port, String MailUsername, String MailPassword) {  
        Auth au = new Auth(MailUsername, MailPassword);  
        // 设置系统属性  
        props = java.lang.System.getProperties(); // 获得系统属性对象  
        props.put("mail.smtp.host", SMTPHost); // 设置SMTP主机  
        props.put("mail.smtp.port", Port); // 设置服务端口号  
        props.put("mail.smtp.auth", "true");// 同时通过验证  
        // 获得邮件会话对象   
        mailSession = Session.getInstance(props, au);  
    }  
    
    public boolean sendingMimeMail(String MailFrom, String MailTo,  
            String MailCopyTo, String MailBCopyTo, String MailSubject,  
            String MailBody) {  
        try {   
            // 创建MIME邮件对象  
            mimeMsg = new MimeMessage(mailSession);  
            // 设置发信人  
            mimeMsg.setFrom(new InternetAddress(MailFrom));  
            // 设置收信人  
            if (MailTo != null) {  
                mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress  
                        .parse(MailTo));  
            }   
            // 设置抄送人  
            if (MailCopyTo != null) {  
                mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC,  
                        InternetAddress.parse(MailCopyTo));  
            }  
            // 设置暗送人  
            if (MailBCopyTo != null) {  
                mimeMsg.setRecipients(javax.mail.Message.RecipientType.BCC,  
                        InternetAddress.parse(MailBCopyTo));  
            }  
            // 设置邮件主题   
            mimeMsg.setSubject(MailSubject, "gb2312");  
            // 设置邮件内容,将邮件body部分转化为HTML格式  
            mimeMsg.setContent(MailBody, "text/html;charset=gb2312");  
            //mimeMsg.setDataHandler(new javax.activation.DataHandler(  
                //  new StringDataSource(MailBody, "text/html")));  
            // 发送邮件  
            Transport.send(mimeMsg);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  
}  

第三步 选取邮件模板

private boolean sendmail(String mailto,String username){  
        String MailTo=mailto;  
        String MailSubject="Westlake International - Application Received";  
        String MailBCopyTo="";  
        String MailCopyTo="";  
        String MailBody="<p><img alt="westlakelogo" src="http://www.expertsonchina.com/images/top.gif" border="0" /></p>"  
        +"<p>J2EE 邮件测试, 亲爱的 "+username+",<br />" +  
                "<br />" +  
                "   欢迎您,您已经注册成功。</p>" +  
                "   <p>We'd like to thank you for your interest in our expert   network business. We appreciate you taking time to apply for membership in our   expert community.</p>" +  
                "   <p>To ensure the integrity and quality of our network, we seek to verify the   credentials of our experts. We hope that you understand it. We will send you a   confirmation email shortly.</p>" +  
                "   <p>Best regards,<br />" +  
                "     <br />  Westlake International Team </p>  <p> </p>";  
        String SMTPHost = Servletconf.getInitParameter("smtphost");  
        String Port=Servletconf.getInitParameter("port");  
        String MailUsername = Servletconf.getInitParameter("mailusername");  
        String MailPassword = Servletconf.getInitParameter("mailpassword");  
        String MailFrom = Servletconf.getInitParameter("mailfrom");  
        if(SMTPHost==null||SMTPHost==""||MailUsername==null||MailUsername==""||MailPassword==null||MailPassword==""||MailFrom==null||MailFrom=="")  
        {  
            System.out.println("Servlet parameter Wrongs");  
        }  
        SendMail send=new SendMail(SMTPHost,Port,MailUsername,MailPassword);  
        if(send.sendingMimeMail(MailFrom, MailTo, MailCopyTo, MailBCopyTo, MailSubject, MailBody)){  
            return true;  
        }  
        else  
        {  
            return false;  
        }  
    }  
    private void toResponse(HttpServletResponse response,String toString) throws IOException  
    {  
        response.setCharacterEncoding("gb2312");  
        PrintWriter out=response.getWriter();  
        out.println(toString);  
    }  
  
}  

SMTP
SMTP (Simple Mail Transfer Protocol,简单邮件传输协议)由RFC 821定义。它定义了发送电子邮件的机制。


POP
POP(Post Office Protocol)代表邮局协议


IMAP
IMAP是更高级的用于接收消息的协议。在RFC 2060中被定义,IMAP代表Internet消息访问协议(Internet Message Access Protocol),目前使用的是版本4,因此也称IMAP4。


MIME
MIME代表多用途Internet邮件扩展标准(Multipurpose Internet Mail Extensions)。它不是邮件传输协议,但对传输内容的消息、附件及其他内容定义了格式。

        积极竞争
    不惧失败
学习提升
原文地址:https://www.cnblogs.com/acmez/p/13609229.html