Java发送电子邮件

来源:互联网 发布:淘宝如何看买家评价 编辑:程序博客网 时间:2024/05/22 07:01

准备两个jar包 JavaMail API 和 Java Activation Framework JAF
http://static.runoob.com/download/mail.jar
http://static.runoob.com/download/activation.jar


邮箱需要开通SMTP服务


import javax.mail.*;import javax.mail.Message.RecipientType;import javax.mail.internet.*;import com.sun.mail.util.MailSSLSocketFactory;import javax.activation.*;import java.util.*;public class MailDemo{    public static void main(String[] arg) throws Exception{        Properties prop = new Properties();        prop.setProperty("mail.transport.protocol","smtp");//连接时的协议                    prop.setProperty("mail.smtp.host","smtp.126.com");//主机名        //prop.setProperty("mail.smtp.host","smtp.qq.com");        prop.setProperty("mail.smtp.port","25");//主机端口号         prop.setProperty("mail.smtp.auth","true");//是否开启权限控制                    prop.setProperty("mail.smtp.ssl.enable","true");//ssl加密        prop.setProperty("mail.debug","true");//如果设置为true,则在发送邮件时会打印发送的信息        //创建程序到邮件服务器之间的一次会话        Session session = Session.getInstance(prop);        //获取邮件对象        Message msg = new MimeMessage(session);//获取信封        msg.setFrom(new InternetAddress("**发送方邮箱**"));        msg.setRecipients(RecipientType.TO,new InternetAddress[]{new InternetAddress("**收件人邮箱**")});        msg.setSubject("这是来自java程序的一封邮件");//标题        msg.setText("这是邮件的正文。。。。内容。。。。");//内容        //找到邮寄员        Transport trans = session.getTransport();//        trans.connect("**发送方邮箱**","**授权码**");        trans.sendMessage(msg,msg.getAllRecipients());/    }}

建议不要使用QQ 邮箱,
笔者最开始用的QQ 邮箱,但一直报错,问过百老师后 QQ 邮箱需要 SSL 加密。其他比如163、新浪邮箱不需要 SSL 加密。


实例2

import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class SendmailUtil {    // 设置服务器    private static String KEY_SMTP = "mail.smtp.host";    private static String VALUE_SMTP = "smtp.qq.com";    // 服务器验证    private static String KEY_PROPS = "mail.smtp.auth";    private static boolean VALUE_PROPS = true;    // 发件人用户名、密码    private String SEND_USER = "2569000943@qq.com";    private String SEND_UNAME = "2569000943";    private String SEND_PWD = "********";    // 建立会话    private MimeMessage message;    private Session s;    /*     * 初始化方法     */    public SendmailUtil() {        Properties props = System.getProperties();        props.setProperty(KEY_SMTP, VALUE_SMTP);        props.put(KEY_PROPS, "true");        //props.put("mail.smtp.auth", "true");        s =  Session.getDefaultInstance(props, new Authenticator(){              protected PasswordAuthentication getPasswordAuthentication() {                  return new PasswordAuthentication(SEND_UNAME, SEND_PWD);              }});        s.setDebug(true);        message = new MimeMessage(s);    }    /**     * 发送邮件     *      * @param headName     *            邮件头文件名     * @param sendHtml     *            邮件内容     * @param receiveUser     *            收件人地址     */    public void doSendHtmlEmail(String headName, String sendHtml,            String receiveUser) {        try {            // 发件人            InternetAddress from = new InternetAddress(SEND_USER);            message.setFrom(from);            // 收件人            InternetAddress to = new InternetAddress(receiveUser);            message.setRecipient(Message.RecipientType.TO, to);            // 邮件标题            message.setSubject(headName);            String content = sendHtml.toString();            // 邮件内容,也可以使纯文本"text/plain"            message.setContent(content, "text/html;charset=GBK");            message.saveChanges();            Transport transport = s.getTransport("smtp");            // smtp验证,就是你用来发邮件的邮箱用户名密码            transport.connect(VALUE_SMTP, SEND_UNAME, SEND_PWD);            // 发送            transport.sendMessage(message, message.getAllRecipients());            transport.close();            System.out.println("send success!");        } catch (AddressException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (MessagingException e) {            e.printStackTrace();        }    }    public static void main(String[] args) {        SendmailUtil se = new SendmailUtil();        se.doSendHtmlEmail("邮件头文件名", "邮件内容", "798210413@qq.com");    }}

实例3

import java.security.Security;import java.util.Date;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class sendEmail {    public static void main(String[] args) throws AddressException,            MessagingException {        String SEND_USER = "2569000943@qq.com";        String SEND_UNAME = "2569000943";        String SEND_PWD = "********";        String VALUE_SMTP = "smtp.qq.com";        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());        //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";        // Get a Properties object        Properties props = System.getProperties();        // props.setProperty("mail.smtp.host", "smtp.gmail.com");        props.setProperty("mail.smtp.host", "smtp.qq.com");        //props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);        //props.setProperty("mail.smtp.socketFactory.fallback", "false");         props.setProperty("mail.smtp.port", "25");        //props.setProperty("mail.smtp.port", "587");        //props.setProperty("mail.smtp.socketFactory.port", "25");        //props.setProperty("mail.smtp.socketFactory.port", "587");        props.put("mail.smtp.auth", "true");        final String username = "2569000943";        final String password = "chHorse123";        Session session = Session.getDefaultInstance(props,                new Authenticator() {                    protected PasswordAuthentication getPasswordAuthentication() {                        return new PasswordAuthentication(username, password);                    }                });        // -- Create a new message --        session.setDebug(true);        Message msg = new MimeMessage(session);        // -- Set the FROM and TO fields --        msg.setFrom(new InternetAddress(username + "@qq.com"));        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(                "798210413@qq.com", false));        msg.setSubject("Hello---");        msg.setText("How are you");        msg.setSentDate(new Date());        Transport transport = session.getTransport("smtp");        // smtp验证,就是你用来发邮件的邮箱用户名密码        transport.connect(VALUE_SMTP, SEND_UNAME, SEND_PWD);        // 发送        transport.sendMessage(msg, msg.getAllRecipients());        Transport.send(msg);        transport.close();        System.out.println("Message sent.");    }}

http://blog.csdn.net/xyang81/article/details/7672745

0 0