Spring Boot – 使用Java List发送电子邮件给多个收件人不起作用

huangapple go评论76阅读模式
英文:

Spring Boot - sending email to multiple receipient using Java List not working

问题

I'm here to provide the translated content as requested. Here is the translated text from your provided content:

我正在尝试使用Spring Boot向多个用户发送邮件。虽然在不使用"Java List"的情况下,"mailRequest.getTo().toString()" 在 "send" 中可以用于一个用户。但是当我尝试使用 "Java List" 将邮件发送给多个收件人时,出现了错误。我正在使用 "SMTP" 服务器,并且已经设置了授权连接为 "true"。

我的来自Swagger UI的JSON输入如下:

"fromEmail": "******@Webmail.abc",
"fullName": "Your Name",
"message": "Hello, this is a test email sending from Our App",
"subject": "Greetings",
"to": [
"XXXXXXX@gmail.com", "XXXXXXX@gmail.com"
]


**错误日志**:

org.springframework.mail.MailParseException: 无法解析邮件;嵌套异常是 javax.mail.internet.AddressException: 字符串 "[Ljava.lang.String;@6d38bf8" 的位置 27 处缺少 "]"。
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:384) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:366) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at com.mail.app.service.impl.MailerServiceImpl.send(MailerServiceImpl.java:51) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.interceptor.AsyncExecutionAspectSupport.lambda$doSubmit$3(AsyncExecutionAspectSupport.java:276) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: javax.mail.internet.AddressException: 缺少 "]"
Caused by: javax.mail.internet.AddressException: 缺少 "]"

at javax.mail.internet.InternetAddress.parse(InternetAddress.java:984) ~[jakarta.mail-1.6.5.jar:1.6.5]
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:728) ~[jakarta.mail-1.6.5.jar:1.6.5]
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:705) ~[jakarta.mail-1.6.5.jar:1.6.5]
at org.springframework.mail.javamail.MimeMessageHelper.parseAddress(MimeMessageHelper.java:711) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:597) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at com.mail.app.service.impl.MailerServiceImpl.lambda$send$1(MailerServiceImpl.java:45) ~[main/:na]
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:375) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 15 common frames omitted


**MailController** 类:
```java
@RestController
@RequestMapping("/email")
public class MailController {

    @Autowired
    private MailService mailService;
    public MailController(MailService mailService){
        this.mailService = mailService;
    }
    @PostMapping("/send")
    @ResponseStatus(HttpStatus.CREATED)
    public void send(@RequestBody MailRequest mailRequest){
        mailService.send(mailRequest);
    }
}

MailRequest 类:(从Swagger UI接收JSON值)

@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class MailRequest {
	private String fullName;
	private List<String> to;  // private String to; works 
	private String fromEmail;
	private String subject;
	private String message;

	//Map<String, String> parameters;
}

MailBuilder 类:

public class MailBuilder {
	private Mail mail = new Mail();
	
	public Mail build() {
		return mail;
	}
	
	public MailBuilder to(String newTo) {
		if (mail.getTo() == null) mail.setTo(new ArrayList<>());
		mail.getTo().add(newTo);
		return this;
	}
	
	public MailBuilder from(String newfrom) {
		if(mail.getFrom() == null) mail.setFrom(newfrom);
		return this;
	}
	
	// other codes go here
}

MailService 类:

@Component
public class MailServiceImpl implements MailService {
	@Autowired private MailerService mailerService;
	@Autowired private MailerConfig mailerConfig;
	@Autowired private TemplateEngine templateEngine;
	
	private final String MAIL_TEMPLATE = "mail";

	@Override
	public void send(MailRequest mailRequest) {
		Map<String, Object> body = new HashMap<>();
		body.put("fromEmail", mailRequest.getFromEmail());
		body.put("message", mailRequest.getMessage());
		mailerService.send(new MailBuilder()
        		.to(mailRequest.getTo().toString())
        		.from(mailRequest.getFromEmail())
        		.subject(mailRequest.getSubject())


<details>
<summary>英文:</summary>

I am trying to send a mail to multiple number of users using Spring Boot. Though without using ```Java list```, ```mailRequest.getTo().toString()``` in ```send``` is working for one user. But when I am trying to send it using ```Java List``` to multiple recipients, it is showing error. I&#39;m using ```SMTP``` server and auth connection is given ```true```.

My json input from swagger UI was:

"fromEmail": "******@Webmail.abc",
"fullName": "Your Name",
"message": "Hello, this is a test email sending from Our App",
"subject": "Greetings",
"to": [
"XXXXXXX@gmail.com", "XXXXXXX@gmail.com"
]


**Error Log**:

org.springframework.mail.MailParseException: Could not parse mail; nested exception is javax.mail.internet.AddressException: Missing ']' in string ``[Ljava.lang.String;@6d38bf8'' at position 27
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:384) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:366) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at com.mail.app.service.impl.MailerServiceImpl.send(MailerServiceImpl.java:51) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.aop.interceptor.AsyncExecutionAspectSupport.lambda$doSubmit$3(AsyncExecutionAspectSupport.java:276) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: javax.mail.internet.AddressException: Missing ']'
Caused by: javax.mail.internet.AddressException: Missing ']'

at javax.mail.internet.InternetAddress.parse(InternetAddress.java:984) ~[jakarta.mail-1.6.5.jar:1.6.5]
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:728) ~[jakarta.mail-1.6.5.jar:1.6.5]
at javax.mail.internet.InternetAddress.parse(InternetAddress.java:705) ~[jakarta.mail-1.6.5.jar:1.6.5]
at org.springframework.mail.javamail.MimeMessageHelper.parseAddress(MimeMessageHelper.java:711) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.mail.javamail.MimeMessageHelper.setTo(MimeMessageHelper.java:597) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at com.mail.app.service.impl.MailerServiceImpl.lambda$send$1(MailerServiceImpl.java:45) ~[main/:na]
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:375) ~[spring-context-support-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 15 common frames omitted

**MailController** Class:

@RestController
@RequestMapping("/email")
public class MailController {

@Autowired
private MailService mailService;
public MailController(MailService mailService){
    this.mailService = mailService;
}
@PostMapping(&quot;/send&quot;)
@ResponseStatus(HttpStatus.CREATED)
public void send(@RequestBody MailRequest mailRequest){
    mailService.send(mailRequest);
}

}

**MailRequest Class**:(Which takes json value from swagger UI)

@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class MailRequest {
private String fullName;
private List<String> to; // private String to; works
private String fromEmail;
private String subject;
private String message;

//Map&lt;String, String&gt; parameters;

}


**MailBuilder** Class:

public class MailBuilder {
private Mail mail = new Mail();

public Mail build() {
	return mail;
}

public MailBuilder to(String newTo) {
	if (mail.getTo() == null) mail.setTo(new ArrayList&lt;&gt;());
	mail.getTo().add(newTo);
	return this;
}

public MailBuilder from(String newfrom) {
	if(mail.getFrom() == null) mail.setFrom(newfrom);
	return this;
}

// other codes go here

}


**MailService** Class:

@Component
public class MailServiceImpl implements MailService {
@Autowired private MailerService mailerService;
@Autowired private MailerConfig mailerConfig;
@Autowired private TemplateEngine templateEngine;

private final String MAIL_TEMPLATE = &quot;mail&quot;;

@Override
public void send(MailRequest mailRequest) {
	Map&lt;String, Object&gt; body = new HashMap&lt;&gt;();
	body.put(&quot;fromEmail&quot;, mailRequest.getFromEmail());
	body.put(&quot;message&quot;, mailRequest.getMessage());
	mailerService.send(new MailBuilder()
    		.to(mailRequest.getTo().toString())
    		.from(mailRequest.getFromEmail())
    		.subject(mailRequest.getSubject())
    		.body(templateEngine, MAIL_TEMPLATE, body)
    		.build());
	
}

}


</details>


# 答案1
**得分**: 1

尝试将`MailBuilder`中的`to`方法更改为接受List。

```java
public MailBuilder to(List<String> emails) {
    if (mail.getTo() == null) mail.setTo(new ArrayList<>());
    mail.getTo().addAll(emails);
    return this;
}

并且只需将邮件列表传递给构建器.to(mailRequest.getTo()),而不是使用toString()

英文:

Try to change to method in MailBuilder to accept List.

public MailBuilder to(List&lt;String&gt; emails) {
    if (mail.getTo() == null) mail.setTo(new ArrayList&lt;&gt;());
    mail.getTo().addAll(emails);
    return this;
}

and just pass list of emails to builder .to(mailRequest.getTo()) instead of toString().

答案2

得分: 0

List.toString()不会提供一个可解析的漂亮输出。它可能需要是逗号分隔的电子邮件列表。

尝试这样做:

mailerService.send(new MailBuilder()
        .to(mailRequest.getTo().stream().collect(Collectors.joining(",")))
        .from(mailRequest.getFromEmail())
        .subject(mailRequest.getSubject())
        .body(templateEngine, MAIL_TEMPLATE, body)
        .build());
英文:

List.toString() will not provide nice output that would be parsable. It probably needs to be comma separated list of emails.

Try doing something like this

        mailerService.send(new MailBuilder()
                .to(mailRequest.getTo().stream().collect(Collectors.joining(&quot;,&quot;)))
                .from(mailRequest.getFromEmail())
                .subject(mailRequest.getSubject())
                .body(templateEngine, MAIL_TEMPLATE, body)
                .build());

huangapple
  • 本文由 发表于 2020年8月11日 17:55:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63355783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定