JAVAWEB practice-mailbox server, mailbox sending test, regular email blessing

1. Introduction to Mailbox Server

1. The basic concept of mailbox server

  • Mail client: it can be installed only on the computer or in the form of a web page
  • Mail server: play the role of receiving and pushing mail
  • Protocol for sending mail: POP3, IMAP4, SMTP

2. Email sending process

Simply put, we send emails, or accept emails sent by others. IMAP4 protocol and SMTP protocol help us realize it.
We need to fetch mail, read mail, and right click are all POP3 protocol to help us achieve.
Insert picture description here

3. Mailbox server installation

Step 1: Double-click the mailbox server software

Step 2: Configure the mailbox server

Double-click the interface to find Tools -> Server Settings -> Then set the content of the server

Insert picture description here
Step 3: Create a new account

Back to the interface -> Account -> New Account

Insert picture description here

4. Email client installation

After downloading Formail from the App Store and
registering successfully, find Settings -> System -> Account Settings, and create the corresponding account entered in the server.
Insert picture description here

Two, use code to send mail

Step 1: Import the jar package

Insert picture description here

Step 2: Modify MainUtils

public class MailUtils {
    
    
	//email:邮件发给谁 subject:表示主题  emailMsg:邮件的内容
	public static void sendMail(String email,String subject, String emailMsg)
			throws AddressException, MessagingException, GeneralSecurityException {
    
    
	
		//创建一个程序与邮件服务器会话对象Session
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");//发邮件协议——SMTP
		props.setProperty("mail.host", "smtp.qq.com");		//发送邮件的服务器地址
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true
		
        props.put("mail.smtp.ssl.socketFactory",sf);
		//创建验证器
		Authenticator auth = new Authenticator() {
    
    
			public PasswordAuthentication getPasswordAuthentication() {
    
    
				return new PasswordAuthentication("2322517484", "032426zyl,.");//发邮件的账号的验证
			}
		};
		//此时并非HttpSession
		Session session = Session.getInstance(props, auth);
		
		// 创建一个Message,相当于邮件的内容
		Message message = new MimeMessage(session);

		message.setFrom(new InternetAddress("[email protected]")); // 设置发送者

		message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 谁是接收者

		message.setSubject(subject);

		message.setContent(emailMsg, "text/html;charset=utf-8");

		// 3.创建 Transport用户将邮件发送

		Transport.send(message);
	}
}

The third step: do the test:

public class SendMailTest {
    
    
	public static void main(String[] args) throws GeneralSecurityException {
    
    
		try {
    
    
			MailUtils.sendMail("[email protected]","测试","此为此时邮件");
		} catch (AddressException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

Three, send email demo regularly

Step 1: Prepare the database
Insert picture description here
Step 2: Guide the package
Insert picture description here
Step 4: Do the test

 public class BirthdayListener implements ServletContextListener{
    
    
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
    
    
		//当web应用启动开启任务调动——功能在用户的生日当天发送邮件
		Timer timer =new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
    
    
			
			@Override
			public void run() {
    
    
				// 为当前的生日的用户进行发邮件
				//1.获得当前过生日的人
				//获得今天过生日人的信息
				SimpleDateFormat format =new SimpleDateFormat("MM-dd");
				String currentDate= format.format(new Date());
				//根据当前时间从数据查询今天过生日的人
				QueryRunner queryRunner =new QueryRunner(DataSourceUtils.getDataSource());
				String sql="SELECT * FROM users WHERE birthday like ?";
				List <User>users=null;
				try {
    
    
					users= queryRunner.query(sql,new BeanListHandler<User>(User.class),"%"+currentDate);
				} catch (SQLException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//发邮件
				if (users !=null&&users.size()>0) {
    
    
					for (User user : users) {
    
    
						String emailMsg="亲爱的"+user.getUsername()+"生日快了";
						try {
    
    
							MailUtils.sendMail(user.getEmail(), "生日祝福", emailMsg);
							System.out.println("邮件发送完毕");
						} catch (MessagingException | GeneralSecurityException e) {
    
    
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				
				}
			}
		},new Date(),1000*60*60*24);//实际开发中起始时间一定是一个固定的时间
						//实际开发中你的间隔时间为一天,每一天取出当天过生日的人,发送邮件
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
    
    
		
		
	}
}

Step 5: Configure the web.xml file

<listener>
  		<listener-class>com.listener.birthday.BirthdayListener</listener-class>
  </listener>

Sixth step
If we need to implement it, we can set some properties by ourselves in MailUtils

public class MailUtils {
    
    
	//email:邮件发给谁 subject:表示主题  emailMsg:邮件的内容
	public static void sendMail(String email,String subject, String emailMsg)
			throws AddressException, MessagingException, GeneralSecurityException {
    
    
	
		//创建一个程序与邮件服务器会话对象Session
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");//发邮件协议——SMTP
		props.setProperty("mail.host", "smtp.qq.com");		//发送邮件的服务器地址
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true
		
       
		//创建验证器
		Authenticator auth = new Authenticator() {
    
    
			public PasswordAuthentication getPasswordAuthentication() {
    
    
				return new PasswordAuthentication("2322517484", "032426zyl,.");//发邮件的账号的验证
			}
		};
		//此时并非HttpSession
		Session session = Session.getInstance(props, auth);
		
		// 创建一个Message,相当于邮件的内容
		Message message = new MimeMessage(session);

		message.setFrom(new InternetAddress("[email protected]")); // 设置发送者

		message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 谁是接收者

		message.setSubject(subject);

		message.setContent(emailMsg, "text/html;charset=utf-8");

		// 3.创建 Transport用户将邮件发送

		Transport.send(message);
	}
}

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/109284605