简体   繁体   English

使用Java应用程序发送电子邮件

[英]Sending email using java app

Why can't this code send email? 为什么此代码无法发送电子邮件? There are no errors, it just doesn't send. 没有错误,只是没有发送。

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!!!");
    }
}

You instantiate a SendMail object and do nothing with it. 您实例化一个SendMail对象,而对其不执行任何操作。 Maybe you should also execute your send() method. 也许您还应该执行send()方法。

You forgot to call send. 您忘了打电话给发送。 Try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM