1. 程式人生 > 其它 >用java 傳送郵件 給女朋友 ,linux定時執行

用java 傳送郵件 給女朋友 ,linux定時執行

技術標籤:java

突發奇想,就想發個郵件給女朋友,每天早上五點二十發,比較有儀式感
而作為一個程式設計師,怎麼可能手動發呢?
一切為了最快達成目的,所以寫得很簡單
第一步,進入qq郵箱開啟設定

在這裡插入圖片描述
開啟POP3/SMTP服務,記住密碼,後面配置檔案要用
在這裡插入圖片描述

專案結構:
在這裡插入圖片描述

介紹:maven專案,email.properties放配置項

# 發件人
[email protected]
# 收件人
[email protected]
# 郵件傳送的伺服器
email.host=smtp.qq.com
# 授權給第三方登陸的密碼
email.password=xxxxxx

日期處理類(計算在一起已經多久了):

package util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * Description: 日期工具類
 */
public class MyDateUtil {

    /**
     * 將指定的日期字串轉換成日期
     *
     * @param dateStr 日期字串
     * @param pattern 格式
     * @return 日期物件
     */
public static Date parseDate(String dateStr, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = null; try { date = sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } return
date; } }

PropertiesUtil(讀取配置檔案):

public class PropertiesUtil {
    static Properties properties = new Properties();
 
    public static boolean loadFile(String fileName) {
        try {
            InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
            //傳入一個輸入流
            properties.load(in);
        }catch (IOException e) {
            e.printStackTrace();
            System.err.println("讀取配置檔案失敗");
            return false;
        }
        return true;
    }

 
    public static String getPropertyValue(String key){
       String value = properties.getProperty(key);
       return value;
    }
}

SendEmail (傳送郵件):

public class SendEmail {

    /** 設定發件人*/
    private  String from;

    /**設定收件人*/
    private  String to ;

    /**設定郵件傳送的伺服器,這裡為QQ郵件伺服器*/
    private  String host;

    /** 授權給第三方登陸的密碼*/
    private  String password;

    {
    	// 載入配置項
        PropertiesUtil.loadFile("email.properties");
        from = PropertiesUtil.getPropertyValue("email.form");
        to = PropertiesUtil.getPropertyValue("email.to");
        host = PropertiesUtil.getPropertyValue("email.host");
        password = PropertiesUtil.getPropertyValue("email.password");
    }

    public void doSend(String text, long days){
        try {
            //獲取系統屬性
            Properties properties = System.getProperties();

            //SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //設定系統屬性
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.auth", "true");

            //獲取傳送郵件會話、獲取第三方登入授權碼
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(from, password);
                }
            });

            Message message = new MimeMessage(session);

            //防止郵件被當然垃圾郵件處理,披上Outlook的馬甲
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");

            message.setFrom(new InternetAddress(from));

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            //郵件標題
            message.setSubject("在一起的第"+days+"天");

            BodyPart bodyPart = new MimeBodyPart();

            bodyPart.setText(text);

            Multipart multipart = new MimeMultipart();

            multipart.addBodyPart(bodyPart);

            //附件
            bodyPart = new MimeBodyPart();
//            String fileName = "檔案路徑";
//            DataSource dataSource = new FileDataSource(fileName);
//            bodyPart.setDataHandler(new DataHandler(dataSource));
//            bodyPart.setFileName("檔案顯示的名稱");
//            multipart.addBodyPart(bodyPart);

            message.setContent(multipart);

            Transport.send(message);
            System.out.println("=============="+ new Date(System.currentTimeMillis())+"=======================");
            System.out.println(String.format("%d\n傳送成功,內容:\n%s",days,text));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

WordConstant (放置土味情話庫,隨機讀取一個)
我收集加上自己寫的,有一百多一點,節省篇幅,就不放
上來了

public class WordConstant {
    String[] word = {
            "有趣的地方都想去​|比如你的世界",
            "我想在你那裡買一塊地|買什麼地?|買你的死心塌地",
            "你知道你和星星有什麼區別嗎?|星星在天上|而你在我心裡",
            "我十拿九穩|就只差你一吻了",
            "可愛不是長久之計|可愛你是",
            "你知道什麼是重要嗎?|就是你無論多重|我都要你!"
    };
    public String getWord(){
        int ran = (int) (Math.random()*(word.length));
        return word[ran].replace("|","\n");
    }

主類,這裡是最簡單得

public class doMain {
    static long getDate(){
        // 在一起的那一天
        String dateStr1 = "2019-08-01 00:00:00";
         // 獲取日期
        Date date1 = MyDateUtil.parseDate(dateStr1, "yyyy-MM-dd HH:mm:ss");
        
        //現在的時間
        Date date2 = new Date(System.currentTimeMillis());
        
        // 獲取相差的天數
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        long timeInMillis1 = calendar.getTimeInMillis();
        calendar.setTime(date2);
        long timeInMillis2 = calendar.getTimeInMillis();

        return  (timeInMillis2 - timeInMillis1) / (1000L * 60L * 60L * 24L);
    }

    public static void main(String[] args) {
        SendEmail sendEmail = new SendEmail();
        long days = getDate();
        String text = new WordConstant().getWord() + "\n"
                + "                                              --xxx";
        if (days%100 ==0){
            text =  "今天是我們的第 "+ days + "天啦\n" +
                    "接下來也要一起好好努力喲!!";
        }else if ( days % 365 == 0){
            text = "今天是我們的第 "+ days / 365 + "週年啦\n" +
                    "時間真的過得很快呢哎喲喂!!\n" +
                    "我們長長久久又進了一步啦";
        }
        sendEmail.doSend(text, days);
    }
}

然後打包成jar包

略,大家都懂的,不懂也網上很多教程

配置linux新增定時計劃

crontab -e

按a進入編輯模式,在最後新增命令

:wq儲存
20代表20分,5代表早上五點
每天會執行一次,記得路徑不要寫錯

java命令那裡要加上路徑,不然會出現命令找不到的情況,應該是環境沒配置的問題