Home  >  Article  >  Database  >  How to use MySQL and Java to implement a simple email sending function

How to use MySQL and Java to implement a simple email sending function

WBOY
WBOYOriginal
2023-09-22 10:10:59897browse

How to use MySQL and Java to implement a simple email sending function

How to use MySQL and Java to implement a simple email sending function

In today's Internet era, email is widely used for communication between individuals and businesses, so Implementing a simple email sending function is very useful for many developers.

This article will introduce how to use MySQL and Java to implement a simple email sending function, and provide specific code examples.

  1. Create database table structure

First, we need to create a MySQL database and create a table in it to store email-related information. In this example, we assume the database name is "mail" and the table name is "mails".

The following is the SQL statement to create the table structure:

CREATE DATABASE mail;

USE mail;

CREATE TABLE mails (
    id INT PRIMARY KEY AUTO_INCREMENT,
    sender VARCHAR(50),
    receiver VARCHAR(50),
    subject VARCHAR(100),
    body TEXT,
    sent_date DATETIME
);
  1. Write a Java class

Next, we create a Java class to implement email sending Function. In this example, we use JavaMail API to send emails.

First, we need to import the related dependencies of JavaMail API and MySQL connection driver.

import java.util.Properties;

import javax.mail.Authenticator;
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;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class MailSender {
    // 邮件服务器地址
    private static final String SMTP_HOST = "smtp.example.com";
    // 邮件服务器端口
    private static final int SMTP_PORT = 587;
    // 发送者邮箱地址
    private static final String SENDER_EMAIL = "sender@example.com";
    // 发送者邮箱密码
    private static final String SENDER_PASSWORD = "password";

    // 数据库连接池
    private static DataSource dataSource;

    // 初始化数据库连接池
    static {
        dataSource = setupDataSource();
    }

    // 获取数据库连接
    private static DataSource setupDataSource() {
        MysqlDataSource ds = new MysqlDataSource();
        ds.setURL("jdbc:mysql://localhost:3306/mail");
        ds.setUser("root");
        ds.setPassword("password");
        return ds;
    }

    // 发送邮件
    public void sendMail(String receiver, String subject, String body) throws MessagingException, NamingException {
        // 创建会话
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        Session session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SENDER_EMAIL, SENDER_PASSWORD);
            }
        });

        // 创建邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(SENDER_EMAIL));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
        message.setSubject(subject);
        message.setText(body);

        // 发送邮件
        Transport.send(message);

        // 将邮件记录插入数据库
        try (Connection conn = dataSource.getConnection()) {
            String sql = "INSERT INTO mails(sender, receiver, subject, body, sent_date) VALUES (?, ?, ?, ?, NOW())";
            Object[] params = { SENDER_EMAIL, receiver, subject, body };
            QueryRunner runner = new QueryRunner();
            runner.insert(conn, sql, new ScalarHandler<>(), params);
        }
    }
}
  1. Using the mail sending function

It is very simple to use the above-mentioned MailSender class. Just introduce the MailSender class into your application and call its sendMail method to send emails.

public class Main {
    public static void main(String[] args) {
        MailSender sender = new MailSender();
        
        try {
            String receiver = "receiver@example.com";
            String subject = "邮件主题";
            String body = "邮件内容";

            sender.sendMail(receiver, subject, body);
            
            System.out.println("邮件发送成功!");
        } catch (MessagingException | NamingException e) {
            e.printStackTrace();
        }
    }
}

In this example, we use the sendMail method to send an email and store the email-related information in the database.

Summary

This article introduces how to use MySQL and Java to implement a simple email sending function. By using the JavaMail API to send emails and using MySQL to save email records, we can easily implement simple email sending functions.

Hope this article is helpful to you!

The above is the detailed content of How to use MySQL and Java to implement a simple email sending function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn