用java语言完整的实现:邮件发送功能
时间: 2024-02-18 13:05:59 浏览: 88
要实现邮件发送功能,需要使用 JavaMail API 和 Java Activation Framework(JAF)。
以下是一个基本的示例代码,用于发送简单邮件:
```java
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailSender {
public static void sendEmail(String fromEmail, String password, String toEmail, String subject, String messageBody) {
String host = "smtp.gmail.com";
int port = 587;
String starttls = "true";
String auth = "true";
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", starttls);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.debug", debug);
Session session = Session.getInstance(props);
session.setDebug(debug);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setSubject(subject);
message.setText(messageBody);
Transport transport = session.getTransport("smtp");
transport.connect(host, fromEmail, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们使用了 Gmail SMTP 服务器来发送邮件。如果你使用其他 SMTP 服务器,需要更改 `host` 和 `port` 变量的值。
要使用该代码,只需调用 `sendEmail` 方法,传递发件人邮箱地址、密码、收件人邮箱地址、邮件主题和邮件内容作为参数。
```java
EmailSender.sendEmail("sender@gmail.com", "password", "recipient@gmail.com", "Test Email", "This is a test email.");
```
需要注意的是,你必须有发件人邮箱地址和密码才能发送邮件。如果你使用的是 Gmail,你可能需要在你的 Gmail 账户中启用“允许 less secure apps 访问”选项。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)