繁体   English   中英

如何使用Java发送电子邮件到表单数据库?

[英]How to send emails form database with Java?

我正在开发我的项目,我想从Java应用程序中的数据库发送电子邮件。 我已经与我的数据库建立连接,可以在其中提取电子邮件,主题,正文和附件。 另外,我还创建了发送与电子邮件服务器连接的电子邮件的代码。 我想要将这两个代码结合在一起,我希望数据库中的信息填充到我的“发送电子邮件”代码中。 这是我在Java中连接数据库的代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Connect {

    public static void main(String[] args) {

        Connection conn = null;
        String dbName = "Employee";
        String serverip="100.00.000.000";
        String serverport="3316";
        String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
        Statement stmt = null;
        ResultSet result = null;
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String databaseUserName = "sys";
        String databasePassword = "123";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
            stmt = conn.createStatement();
            result = null;
            String emailTo,emailSubject,emailBody,emailAttachments;
            result = stmt.executeQuery("Select * From Employees");

            while (result.next()) {
                emailTo =result.getString("emailTo");
                emailSubject = result.getString("emailSubject");
                emailBody = result.getString("emailBody");
                emailAttachments = result.getString("emailAttachments");
                System.out.println(emailTo +  " /" + emailSubject + " /" + emailBody + " /" + emailAttachments);
            }

            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是我发送电子邮件的代码:

import java.util.Properties;     
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Send {

    public static void main(String[] args) {

        final String username = "work@gmail.com";
        final String password = "1234";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "100.00.000.000");
        props.put("mail.smtp.port", "20");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("work@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("Here I want to use emailTo from my Database"));
            message.setSubject("Here emailSubject");
            message.setText("Here emailBody");
            message.setAttachment("Here emailAttachments");

            Transport.send(message);

            System.out.println("Success");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

如果有人可以帮助您将其组合起来,请告诉我。 提前致谢。

您好,您始终必须尝试解耦代码并寻找最佳实践,为了使用dao和解耦类,我在源代码中进行了一些修改,您还需要修改许多其他内容,但这是一个很好的开始。 检查下一个链接以了解一些OOP概念http://docs.oracle.com/javase/tutorial/java/concepts/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

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

class Employee {
    private String emailTo;
    private String emailSubject;
    private String emailBody;
    private String emailAttachments;

    public Employee() {
        // TODO Auto-generated constructor stub
    }

    public Employee(String emailTo, String emailSubject, String emailBody,
            String emailAttachments) {
        super();
        this.emailTo = emailTo;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;
        this.emailAttachments = emailAttachments;
    }

    public String getEmailTo() {
        return emailTo;
    }

    public void setEmailTo(String emailTo) {
        this.emailTo = emailTo;
    }

    public String getEmailSubject() {
        return emailSubject;
    }

    public void setEmailSubject(String emailSubject) {
        this.emailSubject = emailSubject;
    }

    public String getEmailBody() {
        return emailBody;
    }

    public void setEmailBody(String emailBody) {
        this.emailBody = emailBody;
    }

    public String getEmailAttachments() {
        return emailAttachments;
    }

    public void setEmailAttachments(String emailAttachments) {
        this.emailAttachments = emailAttachments;
    }

}

class EmployeeDao {
    private Connection con;

    private static final String GET_EMPLOYEES = "Select * From Employees";

    private void connect() throws InstantiationException,
            IllegalAccessException, ClassNotFoundException, SQLException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                .newInstance();
        con = DriverManager
                .getConnection("jdbc:sqlserver://100.00.000.000\\SQLEXPRESS:3316;databaseName=Employee");
    }

    public List<Employee> getEmployees() throws Exception {
        connect();
        PreparedStatement ps = con.prepareStatement(GET_EMPLOYEES);
        ResultSet rs = ps.executeQuery();
        List<Employee> result = new ArrayList<Employee>();
        while (rs.next()) {
            result.add(new Employee(rs.getString("emailTo"), rs
                    .getString("emailSubject"), rs.getString("emailBody"), rs
                    .getString("emailAttachments")));
        }
        disconnect();
        return result;
    }

    private void disconnect() throws SQLException {
        if (con != null) {
            con.close();
        }
    }
}

class EmailSender {
    private Session session;

    private void init() {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "100.00.000.000");
        props.put("mail.smtp.port", "20");

        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("work@gmail.com", "1234");
            }
        });
    }

    public void sendEmail(Employee e) throws MessagingException {
         init();
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress("work@gmail.com"));
         message.setRecipients(Message.RecipientType.TO,
             InternetAddress.parse(e.getEmailTo()));
         message.setSubject(e.getEmailSubject());
         message.setText(e.getEmailBody());
         Transport.send(message);
    }
    public void sendEmail(List<Employee> employees) throws MessagingException{
        for (Employee employee : employees) {
            sendEmail(employee);
        }
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        EmployeeDao dao=new EmployeeDao();
        List<Employee> list=dao.getEmployees();
        EmailSender sender=new EmailSender();
        sender.sendEmail(list);
    }
}

暂无
暂无

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

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