zoukankan      html  css  js  c++  java
  • Java发送邮件的简单实现

    使用Oracle官方的JavaMail进行实现,JavaMail下载地址:https://java.net/projects/javamail/pages/Home
    将下载好的jar包加入到工程路径中就OK了,我使用的是最新的1.5.2版本号的javax.mail.jar。

    关于邮件协议可參考:什么是POP3、SMTP和IMAP?
    以下的演示样例中是通过我的新浪邮箱(theonegis@sina.cn)给QQ邮箱(123456789@qq.com不知道是谁的邮箱)发邮件。以下给出实现代码:

    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.MimeMessage;
    
    public class SimpleMail {
        public static void main(String[] args) {
            Properties props = new Properties();
            //这里使用smtp协议发送邮件。我的新浪邮箱是.cn的不是.com的,所以smtpserver为smtp.sina.cn
            props.put("mail.smtp.host", "smtp.sina.cn");
            Session session = Session.getInstance(props, null);
    
            try {
                MimeMessage msg = new MimeMessage(session);
                //设置发件人邮箱
                msg.setFrom("theonegis@sina.cn");
                //设置收件人邮箱
                msg.setRecipients(Message.RecipientType.TO, "123456789@qq.com");
                //设置主题
                msg.setSubject("This is a test");
                //设置日期
                msg.setSentDate(new Date());
                //设置正文内容
                msg.setText("How are you?

    This is a test, please do not reply!"); //发送邮件,參数为邮件信息,发件人邮箱和发件人邮箱password Transport.send(msg, "theonegis@sina.cn", "这里是发件人的password"); } catch (MessagingException mex) { System.err.println("Send failed! Exception: " + mex); } } }

    JavaMail中比較重要的的类是Session、Store和Folder。

  • 相关阅读:
    Maximum of lines in a DataBand
    "New page after" by code
    How to show out three rows from the same databand On A4?
    Asp.Net Core 第07局:路由
    Asp.Net Core 第06局:中间件
    Asp.Net Core 第05局:读取配置
    Asp.Net Core 第04局:依赖注入
    POJ-1003
    ORACLE 存储过程实例 [备忘录]
    关于操作有符号数的溢出问题
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5271279.html
Copyright © 2011-2022 走看看