简体   繁体   中英

How to send emails form database with Java?

I'm working on my project where I want to send emails from my database in java app. I already have connection with my database where I pull out email, subject, body and attachments. Also I have created code that send the emails that is connected with email server. What I want is to combine these two codes together, I want my information from database to populate in my Send Email code. Here is my code for Connecting database in 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();
        }
    }
}

Here is my code that Send Emails:

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

If anyone can help with combining this please let me know. Thanks in advance.

Hello you always have to try to decouple your code and look for the best practices, I made some modifications in your source code in order to use a dao and a decouple your classes, there are many other things that you have to modify but it is a good way to start. Check the next link to learn some OOP concepts 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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