发送邮件

sun的mail-1.4.4.jar

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class sendEmalTest {


    public static void main(String[] args) throws Exception {
        Session session = getSession();
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("test@qq.com"));
        message.addRecipient(Message.RecipientType.TO,new InternetAddress("fasong@qq.com"));
        message.addRecipient(Message.RecipientType.CC,new InternetAddress("chaosong@qq.com"));
        message.addRecipient(Message.RecipientType.BCC,new InternetAddress("misong@qq.com"));
        message.setSubject("title","utf-8");
        Multipart multipart = new MimeMultipart();
        MimeBodyPart bodyContent = new MimeBodyPart();
        bodyContent.setContent("Hello Email!", "text/plain;charset=utf-8");
        multipart.addBodyPart(bodyContent);
        message.setContent(multipart);
        Transport.send(message);
    }

    public static Session getSession(){
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.host", "www.qq.com");
        properties.put("mail.smtp.port", "80");
        properties.put("mail.smtp.auth", "false");
        properties.put("mail.smtp.connectiontimeout", "60000");
        properties.put("mail.smtp.timeout", "300000");
        //需要验证用户密码时 mail.smtp.auth = true
        if(properties.getProperty("mail.smtp.auth") == "true"){
            return Session.getInstance(properties, new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("","");}});
        }

        return Session.getInstance(properties);
    }
}
原文地址:https://www.cnblogs.com/wqff-biubiu/p/9082768.html