簡體   English   中英

使用Java應用程序發送電子郵件

[英]Sending email using java app

為什么此代碼無法發送電子郵件? 沒有錯誤,只是沒有發送。

package tips.mails;

import java.util.Properties;


import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;



public class SendMail {
private String from;
private String to;
private String subject;
private String text;

public SendMail(String from, String to, String subject, String text){
    this.from = from;
    this.to = to;
    this.subject = subject;
    this.text = text;
}

public void send(){

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "465");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(from);
        toAddress = new InternetAddress(to);
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        simpleMessage.setFrom(fromAddress);
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);
        simpleMessage.setText(text);

        Transport.send(simpleMessage);
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

    public static void main(String args[])
    { 
        new SendMail("source", "dist","Subject", "Test Message!!!");
    }
}

您實例化一個SendMail對象,而對其不執行任何操作。 也許您還應該執行send()方法。

您忘了打電話給發送。 嘗試這個

   new SendMail("source", "dist","Subject", "Test Message!!!").send();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM