java 如何通过所以第三方服务商发送邮箱
要通过第三方服务商发送电子邮件,需要使用JavaMail API。下面是一个简单的示例:
首先,需要在pom.xml文件中添加以下依赖项:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
然后,可以编写以下代码来发送电子邮件:
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;
public class EmailSender {
public static void main(String[] args) {
final String username = "your_email_address@gmail.com";
final String password = "your_email_password";
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 Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_email_address@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient_email_address@example.com"));
message.setSubject("Test Email");
message.setText("This is a test email from Java.");
Transport.send(message);
System.out.println("Email sent.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
在这个示例中,我们使用了Gmail作为SMTP服务器。如果您使用其他服务提供商,请相应地更改SMTP服务器地址和端口号。此外,我们使用了用户名和密码来进行身份验证。请确保替换为您自己的电子邮件地址和密码
原文地址: https://www.cveoy.top/t/topic/hjca 著作权归作者所有。请勿转载和采集!