码迷,mamicode.com
首页 > 其他好文 > 详细

MyEmail

时间:2016-09-29 20:48:41      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyEmail
{
    private static Session session; //邮件会话
    private static String host_properties = "mail_host.properties";
    private static Logger logger = LoggerFactory.getLogger(MyEmail.class);
   
    static
    {
        Properties properties = null;
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(host_properties);
        try
        {
            properties.load(in);
        } catch(IOException e)
        {
            logger.error("加载邮件服务器信息失败", e.getMessage());
        }
        session = Session.getDefaultInstance(properties, null);//null表示无邮件授权
    }

    public MimeMessage createMimeMessage(String addr)
    {
        MimeMessage message = new MimeMessage(session);
        //在建立了MimeMessage对象,需设置它的各个part,对于MimeMessage类而言,part == 接口
        try
        {
            message.setSubject("It‘s my test - email!");//设置邮件主题
            message.setText("Hello, are u suprized?");
            Address address  = new InternetAddress(addr);//收件人
            message.setFrom(address);
            message.addRecipient(javax.mail.Message.RecipientType.TO, address);
            message.saveChanges();
        } catch(MessagingException e)
        {
            e.printStackTrace();
        }
        
        return message;
    }
    
    public void sendEmail(String addr)
    {
        MimeMessage message = createMimeMessage(addr);
        Transport transport;
        try
        {
            transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch(NoSuchProviderException e)
        {
            e.printStackTrace();
        } catch(MessagingException e)
        {
            e.printStackTrace();
        }
    }
}

 http://www.cnblogs.com/gisblogs/p/4362937.html

MyEmail

标签:

原文地址:http://www.cnblogs.com/ld-swust/p/5920770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!