gpt4 book ai didi

java - 使用 PlayFramework 发送邮件

转载 作者:行者123 更新时间:2023-11-30 10:35:21 27 4
gpt4 key购买 nike

应用程序.conf

play.mailer {
host=smtp.gmail.com
port=25
ssl=true
tls=false
user="wahid.****.com"
password="A******f"
debug=false
mock=false
}

构建.sbt

"com.typesafe.play" %% "play-mailer" % "5.0.0"

我的 Controller

public class MySampleMail {

@Inject MailerClient mailerClient;

public void sendEmail() {
String cid = "1234";
Email email = new Email()
.setSubject("Simple email")
.setFrom("wahid.************.com")
.addTo("w***********.com")
.setBodyText("A text message");
mailerClient.send(email);
}
}

但是这个发送(电子邮件)给出了执行异常[[CompletionException: java.lang.NullPointerException]]

最佳答案

试试这个:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class Main
private static String USER_NAME = "+++++++++++++++"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "++++++++++"; // GMail password
private static String RECIPIENT = "++++++++++++++";

public static void mainMethod() {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";

sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);

try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];

// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}

for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}

message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}

关于java - 使用 PlayFramework 发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com