javamail发送邮件,支持yahoo,google,163.com,qq.com邮件发送

阅读更多

最近项目发邮件程序出了问题,发现无法支持smtp.gmail.com邮件服务器,在网上查了些资料,找到了支持gmail邮件发送的处理方法,并做了测试验证:

 

有关javamail各个属性的介绍,请查看以下网址:

http://javamail.kenai.com/nonav/javadocs/com/sun/mail/smtp/package-summary.html

 

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 MyMailSender
{
    private String hostName = "smtp.gmail.com";
    private String userName = "******";
    private String userPwd = "******";
    private String fromUserMail = "******";
    private String toUserMail = "******";

    public void sendTestMail() throws AddressException, MessagingException
    {
        Properties mailProps = new Properties();
        mailProps.setProperty("mail.smtp.host", this.hostName);
        mailProps.setProperty("mail.smtp.starttls.enable", "true");
        mailProps.setProperty("mail.smtp.auth", "true");
        mailProps.setProperty("mail.smtp.quitwait", "false");

        //如果不要对服务器的ssl证书进行受信任检查,测添加以下语句

        //mailProps.setProperty("mail.smtp.ssl.trust","*");

        Session mailSession = Session.getDefaultInstance(mailProps,
                new Authenticator()
                {
                    protected PasswordAuthentication getPasswordAuthentication()
                    {
                        return new PasswordAuthentication(userName, userPwd);
                    }
                });

        Message mailMessage = new MimeMessage(mailSession);
        mailMessage.setFrom(new InternetAddress(this.fromUserMail));
        mailMessage.setRecipients(Message.RecipientType.TO,
                InternetAddress.parseHeader(this.toUserMail, false));

        mailMessage.setSubject("This is a test mail.");
        mailMessage.setText("This is a test mail for gmail");
        mailMessage.setSentDate(new Date());

        Transport.send(mailMessage);
    }

    public static void main(String[] args)
    {
        try
        {
            new MyMailSender().sendTestMail();
        }
        catch (AddressException e)
        {
            e.printStackTrace();
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
    }
}

该程序分别在smtp.gmail.com,smtp.mail.yahoo.com.cn,smtp.qq.com,smtp.163.com上验证过,可以发送成功

你可能感兴趣的:(javamail,gmail,starttls)