Java发送邮件

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

public class sendMail {
    public static void main(String[] args) {
        String from = "cm1@leejay.vip";  //发件人电子邮箱
        String from_pass = "12345678";
        String to = "cm2@leejay.vip";  //收件人电子邮箱
        String server = "172.16.5.187";  //发件邮件的主机服务器
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", server);  //设置邮件服务器
        properties.setProperty("mail.smtp.port", "7250");  //投递系统端口
        properties.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, from_pass);
            }
        });
        try{
            // 通过会话,得到一个邮件,用于发送
            MimeMessage message = new MimeMessage(session); //创建默认的MimeMessage对象
            message.setFrom(new InternetAddress(from)); //设置头部的from
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));//设置头部的收件人
            message.setSubject("This is the java test mail"); //主题
            message.setText("This is java test mail!", "gb18030"); //消息体
            message.setSentDate(new Date());  //设置发送的日期
            Transport.send(message); // 调用transport的send方法发送邮件
            System.out.println("Sent message successfully...");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

posted @ 2021-03-03 14:05  leejay_python  阅读(53)  评论(0编辑  收藏  举报