javamail+ical4j發送會議提醒

本篇講述小編在使用ical4j時對其的理解與使用,留做筆記的同時但願能幫助到你們!html

初學者能夠先了解下ical4j的基本信息:java

iCalender編程基礎,瞭解與使用ical4j:https://www.ibm.com/developerworks/cn/java/j-lo-ical4j/index.htmlnode

廢話很少說直接進入題編程

maven服務器

<!-- 導入ical4j庫 -->
<dependency>
	<groupId>org.mnode.ical4j</groupId>
	<artifactId>ical4j</artifactId>
	<version>1.0.2</version>
</dependency>

<!-- 郵件start -->
<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4.7</version>
</dependency>

  

在經過ical4j與javamail實現會議邀請的時候,過程以下maven

一、經過ical4j建立一個Calendar(日曆),這個Calendar中能夠包括VEvent(事件)、VAlarm(提醒)、TODO(待辦事項)等多項內容。而會議邀請則必需要包含VEvent,若是須要提醒,則能夠包含VAlarm。ide

public static Multipart getContentText() throws Exception {
        // 時區
        TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
        TimeZone timezone = registry.getTimeZone("Asia/Shanghai");
        // 會議地點
        String location = "安徽省合肥市";
        // 會議時間
        java.util.Calendar cal = java.util.Calendar.getInstance();

        cal.setTimeZone(timezone);
        //會議啓動時間
        cal.set(2018, 2 - 1, 13, 13, 45); // 月份是要早一個月
        DateTime start = new DateTime(cal.getTime());
        //會議結束時間
        cal.set(2018, 2 - 1, 13, 18, 55);
        DateTime end = new DateTime(cal.getTime());

        
        // --------事件(VEvent start)----------
        VEvent vevent = new VEvent(start, end, subject);
        vevent.getProperties().add(timezone.getVTimeZone().getTimeZoneId());// 時區
        vevent.getProperties().add(new Location(location));// 會議地點
        vevent.getProperties().add(new Summary(subject));// 郵件主題
        vevent.getProperties().add(new Description(content));// 郵件內容
        vevent.getProperties().add(new UidGenerator("meeting invite").generateUid());// 設置uid
        vevent.getProperties().add(new Organizer(URI.create("mailto:" + from)));
        // 與會人
        Set<String> emailSet = new HashSet<String>();
        emailSet.add(from);
        emailSet.add(to);
        int i = 1;
        for (String email : emailSet) {
            Attendee attendee = new Attendee(URI.create("mailto:" + email));
            if (1 == i) {
                attendee.getParameters().add(Role.REQ_PARTICIPANT);
            } else {
                attendee.getParameters().add(Role.OPT_PARTICIPANT);
            }
            attendee.getParameters().add(new Cn("Developer" + i));
            vevent.getProperties().add(attendee);
            i++;
        }
        // --------VEvent Over----------
        
        
        // --------提醒(VAlarm Start)----------
        // 提早10分鐘提醒
        VAlarm valarm = new VAlarm(new Dur(0, 0, -10, 0));
        // 重複一次
        valarm.getProperties().add(new Repeat(1));
        // 持續十分鐘
        valarm.getProperties().add(new Duration(new Dur(0, 0, 10, 0)));
        
        // 提醒窗口顯示的文字信息
        valarm.getProperties().add(new Summary("Event Alarm"));
        valarm.getProperties().add(Action.DISPLAY);
        valarm.getProperties().add(new Description("Progress Meeting at 9:30am"));
        vevent.getAlarms().add(valarm);// 將VAlarm加入VEvent
        // --------VAlarm Over-------------
        
        
        // --------日曆對象 Start---------------
        Calendar icsCalendar = new Calendar();
        icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
        icsCalendar.getProperties().add(CalScale.GREGORIAN);
        icsCalendar.getProperties().add(Version.VERSION_2_0);
        icsCalendar.getProperties().add(Method.REQUEST);
        icsCalendar.getComponents().add(vevent);// 將VEvent加入Calendar
        // 將日曆對象轉換爲二進制流
        CalendarOutputter co = new CalendarOutputter(false);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        co.output(icsCalendar, os);
        byte[] mailbytes = os.toByteArray();
        // --------日曆對象 Over------------------
        
        
        BodyPart mbp = new MimeBodyPart();
        mbp.setContent(mailbytes, "text/calendar;method=REQUEST;charset=UTF-8");

        MimeMultipart mm = new MimeMultipart();
        mm.setSubType("related");
        mm.addBodyPart(mbp);
        return mm;
    }

  二、事件建立以後,經過javamail發送郵件網站

    private static String from = "***@126.com"; 
    private static String to = "***@126.com";//收件人 
    private static String subject = "test";//標題 
    private static String content = "青空報告總結會議";//郵件內容 
    
    public static void main(String[] args) {
        // 連接郵件服務器
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp"); // 郵件協議
        props.put("mail.smtp.host", "smtp.126.com"); // 服務器域名
        props.put("mail.smtp.auth", "true");
        //帳號密碼認證
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String username = "***@126.com"; // 大多數是你郵件@前面的部分
                String pwd = "******";
                return new PasswordAuthentication(username, pwd);
            }
        };
        Session mailSession = Session.getInstance(props, auth);
        // 獲取Message對象
        Message msg = new MimeMessage(mailSession);
        try {
            // 設置郵件基本信息
            msg.setFrom(new InternetAddress(from));//發件人
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));//收件人
            msg.setSentDate(new java.util.Date());//發送時間
            msg.setSubject(subject);//發送標題
            Multipart mp = getContentText();// 獲取不一樣類型的郵件的郵件內容
            msg.setContent(mp);
            msg.saveChanges();
        } catch (Exception ex) {
        }
        System.out.println(sendEmail(msg));
    }

    public static Boolean sendEmail(Message msg) {
        // 發送郵件
        try {
            Transport.send(msg);
            return true;
        } catch (SendFailedException e) {// 郵件地址無效
            System.out.println(e);
            return false;
        } catch (Exception e) {
            Timer timer = new Timer();
            System.out.println(e);
            return false;
        }
    }

  

使用javamail發送郵件時,須要鏈接郵件服務器,根據不一樣的郵箱填寫不一樣的郵箱服務器域名及協議,具體可百度搜索相關郵箱網站便可查詢ui

例:spa

 網易126免費郵箱相關服務器服務器信息:

 

 郵件服務器名稱 服務器地址  端口號
  POP3服務器 pop.126.com  110
  SMTP服務器 smtp.126.com  25
  IMAP服務器 imap.126.com  143

 qq免費郵箱相關服務器服務器信息:

郵件服務器名稱 服務器地址  端口號
  POP3服務器 pop.qq.com 465
  SMTP服務器 smtp.qq.com 587

 

在帳號密碼認證時,須要開通對應郵箱的受權碼使用受權碼代替郵箱密碼

qq開通受權碼流程:https://jingyan.baidu.com/article/fedf0737af2b4035ac8977ea.html

網易開通受權碼流程:https://jingyan.baidu.com/article/9faa72318b76bf473c28cbf7.html

 

最後附加幾條可能遇到的錯誤信息:

  一、553 Mail from must equal authorized user:這個錯誤網上搜都說是System Admin e-main Address 沒有設置,不過我後來解決是由於設置該屬性的時候沒有配置正確

    mimeMessage.setFrom(new InternetAddress("***@126.com"));

  二、535 Error: authentication failed:這個問題就是上面所說的受權碼的問題了,若是你的pwssword 使用的是郵箱的登陸密碼就會報這個錯誤,須要獲取郵箱的受權碼才能夠

  三、javax.mail.NoSuchProviderException: No provider for pop:郵件協議與服務器域名衝突了,smtp => smtp.126.com,pop => pop.126.com

  四、javax.mail.AuthenticationFailedException: 550 Óû§ÎÞȨµÇ½:用戶名密碼錯誤

       五、com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 126 smtp1:若是出現改錯誤,那麼多是標題或內容中出現了test或helloword等,被網易認爲郵件內容不合法。

    把各項內容按正常的內容填寫以後發送就正常使用了

    具體可參考:http://blog.csdn.net/yiyihuazi/article/details/53671791

    企業退信的常見問題:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

相關文章
相關標籤/搜索