Java实现发送邮件的代码可以使用JavaMail库来完成。以下是一个简单的示例代码:
import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import java.util.Properties;public class SendEmail {public static void main(String[] args) {// 发送方邮箱地址String fromEmail = "your_email@example.com";// 发送方邮箱密码或授权码String password = "your_password";// 接收方邮箱地址String toEmail = "recipient_email@example.com";// 配置SMTP服务器的属性Properties props = new Properties();props.put("mail.smtp.host", "smtp.example.com");props.put("mail.smtp.port", "587");props.put("mail.smtp.auth", "true");props.put("mail.smtp.starttls.enable", "true");// 创建Session对象Session session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(fromEmail, password);}});try {// 创建MimeMessage对象MimeMessage message = new MimeMessage(session);// 设置发件人message.setFrom(new InternetAddress(fromEmail));// 设置收件人message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));// 设置邮件主题message.setSubject("Test Email");// 设置邮件内容message.setText("This is a test email.");// 发送邮件Transport.send(message);System.out.println("Email sent successfully!");} catch (MessagingException e) {e.printStackTrace();}}}请注意,你需要将代码中的"your_email@example.com",“your_password”,“smtp.example.com”,"recipient_email@example.com"替换为你自己的邮箱地址、密码、SMTP服务器地址和接收方邮箱地址。