Java實現郵箱發送驗證碼

來源:互聯網
上載者:User

標籤:rac   成功   end   catch   exception   override   nbsp   internet   jar包   

第一步,匯入JAR包,JAR包[http://pan.baidu.com/s/1kVRvGyF]

正式代碼:

  首先書寫一個工具類:

  MailUtil

import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;/** * 郵件工具類 */public class MailUtil {    /**     * 發送郵件     * @param to 給誰發     * @param text 發送內容     */    public static void send_mail(String to,String text) throws MessagingException {        //建立連線物件 串連到郵件伺服器        Properties properties = new Properties();        //設定發送郵件的基本參數        //發送郵件伺服器        properties.put("mail.smtp.host", "smtp.huic188.com");        //傳送埠        properties.put("mail.smtp.port", "25");        properties.put("mail.smtp.auth", "true");        //設定發送郵件的帳號和密碼        Session session = Session.getInstance(properties, new Authenticator() {            @Override            protected PasswordAuthentication getPasswordAuthentication() {                //兩個參數分別是發送郵件的賬戶和密碼                return new PasswordAuthentication("[email protected]","這裡寫你的帳號的密碼");            }        });        //建立郵件對象        Message message = new MimeMessage(session);        //設定寄件者        message.setFrom(new InternetAddress("[email protected]"));        //設定收件者        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));        //設定主題        message.setSubject("這是一份測試郵件");        //設定郵件內文  第二個參數是郵件發送的類型        message.setContent(text,"text/html;charset=UTF-8");        //發送一封郵件        Transport.send(message);    }}

測試類別:

  TEST:

import javax.mail.MessagingException;/** * 測試類別 */public class Test {    public static void main(String[] args) {        try {            MailUtil.send_mail("[email protected]", String.valueOf(Math.random() * 999));            System.out.println("郵件發送成功!");        } catch (MessagingException e) {            e.printStackTrace();        }    }}

 

Java實現郵箱發送驗證碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.