有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jar使用java代码发送电子邮件

早上好。我有个问题。我想用eclipse oxygen通过Gmail发送电子邮件。2018年3月3日。我使用了两个罐子:mail-1.4.7和activation 1.1.1。我还允许对我的Gmail账户进行不太安全的访问。这是我的代码:

package Login_sys;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSend {
final String emailSMTPserver = "smtp.gmail.com"; 
final String emailServerPort = "587";
String receiverEmail = null;
String emailSubject = null;
String emailBody = null;
String from = null ;
String password = null ;

public  EmailSend(String from,String password,String subject ,String message,String to)
{

    this.from = from ;
    this.password = password ; 
    this.emailSubject = subject ; 
    this.emailBody = message ;
    this.receiverEmail = to ;

    Properties props = System.getProperties();
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.host", emailSMTPserver);
    props.put("mail.smtp.port", emailServerPort);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", emailServerPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    SecurityManager security = System.getSecurityManager();

    try 
    {
          Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);

            Message msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmail));
            Transport.send(msg);
            System.out.println("send successfully");
        } catch (Exception ex) {
            System.err.println("Error occurred while sending.!");
        }

    }

private class SMTPAuthenticator extends javax.mail.Authenticator {

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(from , password);
    }
}}

我从另一个班级叫它:

 EmailSend f = new EmailSend ("******@gmail.com","*****","Testing","testin  
 email","****@gmail.com"); 

它总是打印:发送时出错。我不知道我的错在哪里


共 (0) 个答案