java发送邮件

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPTransport;

public class sendMailTest
{

    public static void main(String args[])
    {
        String protocol = "smtp"; //协议
        String hostName = "smtp.sina.com.cn"; //SMTP服务器地址
        Properties props = new Properties();
        props.put("mail.transport.protocol", protocol);
        props.put("mail.smtp.host", hostName);
        props.put("mail.smtp.localhost", "localhost");
        props.put("mail.store.protocol", "25");
        props.put("mail.smtp.auth", "true");

        Session mailSession = Session.getInstance(props);
        Message msg = new MimeMessage(mailSession); //邮件信息
        try
        {
            SMTPTransport st = (SMTPTransport)mailSession.getTransport(protocol);
            st.connect(hostName, "***@sina.com", "******"); //***@sina.com为新浪帐号,******为密码
            msg.setFrom(new InternetAddress("[email protected]", "午刀十"));
            msg.setSubject("今天天气真好");
            msg.setContent("要下雨了", "text/html;charset=GBK");
            InternetAddress[] iaRecevers = new InternetAddress[1];
            iaRecevers[0] = new InternetAddress("***@sina.com"); //选择要接收的邮件地址
            msg.setRecipients(Message.RecipientType.TO, iaRecevers);
            st.sendMessage(msg, msg.getAllRecipients());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(mail,SMTPTransport)