java 可以发送邮件的网页
时间: 2024-05-13 16:19:52 浏览: 22
Java可以通过JavaMail API发送邮件。以下是一个简单的Java程序,可以通过Gmail SMTP服务器发送电子邮件。
```java
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 SendEmail {
public static void main(String[] args) {
final String username = "yourusername@gmail.com";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
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("yourusername@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("recipientemail@example.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
在上面的代码中,将`yourusername@gmail.com`和`yourpassword`替换为您自己的Gmail帐户的凭据。然后将`recipientemail@example.com`替换为您要发送电子邮件的收件人的电子邮件地址。执行此代码将在控制台上打印“Done”以指示电子邮件已成功发送。
阅读全文
相关推荐













