如何在Java中发送邮件时支持阿拉伯语单词。

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

how to support Arabic words in java while sending mail

问题

以下是您提供的代码的翻译:

在application.xml中的连接属性:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userdb?useUnicode=yes&characterEncoding=UTF-8
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect 

Pojo类:

class User{
@Id
    @Column(name = "username", unique = true, nullable = false, length = 64)
    private String username;
@Column(name = "password")
    private String password;
@Column(name = "email", length = 100)
    private String email;
//getter和setter
//toString()方法
}

MySQL表属性:

CREATE TABLE `User` (
  `username` varchar(64) CHARACTER SET utf8 NOT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

当我保存阿拉伯字符时,它成功保存到数据库中。

但是当我检索数据时,得到的是像????这样的字符。当我在调试中停在那一点时,我可以看到该对象上的阿拉伯字体是正确的。

邮件发送代码:

private void initSession() {
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");
    props.setProperty("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.debug", "true");
    

    session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
}

public String forgetPassword(String accounts, String e_address) {
    EmailMessage emailMessage = new EmailMessage();
    emailMessage.setSubject("Forget Password");
    emailMessage.setBody(MessageTemplate.forgetPassword(accounts));
    emailMessage.setTo_address(e_address);
    try {
        sendEmail(emailMessage);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return "Successfully send";
}

private void sendmail(EmailMessage emailmessage) throws AddressException, MessagingException, IOException {
    
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(username, false));
    
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailmessage.getTo_address()));
            msg.setSubject(emailmessage.getSubject());
            msg.setContent(emailmessage.getBody(), "text/html");
            msg.setSentDate(new Date());
    
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(emailmessage.getBody(), "text/html");
    
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
    
            msg.setContent(multipart);
            //发送电子邮件
            Transport.send(msg);
    
        }

Service代码:

public String getAllAccount(String email) {
        List<User> users = myUserRepository.findByEmail(email);
        System.out.println(users.toString());
        return users.toString();
    }

Controller代码:

@PostMapping("/forgetPassword")
public ResponseEntity forgetPassword(@RequestBody GetEmail getEmail) {
    ResponseEntity responseEntity;
    Map<String, String> result = new HashMap<>();
    if (!PatternMatch.isValidEmail(getEmail.getEmail())) {
        result.put("result", UserConstant.UNSUPPORTED_EMAIL + "");
    } else {
        String accounts = service.getAllAccount(getEmail.getEmail());
        System.out.println("accounts " + accounts);
        if (accounts.equals("")) {
            result.put("result", UserConstant.EMAIL_NOT_EXISTS + "");
        } else {
            new Thread(() -> {
                final EmailSender sender = EmailSender.getInstance();
                sender.forgetPassword(accounts, getEmail.getEmail());
            }) {
            }.start();
            result.put("result", UserConstant.EMAIL_SENT_SUCCESSFULLY + "");
        }
    }

请注意,代码中可能存在HTML转义字符(如&quot;),您可能需要根据需要进行处理。如果您有任何具体的问题或需要进一步的帮助,请随时提出。

英文:

I have used springboot with JPA. my Codes are

Connection property in application.xml:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userdb?useUnicode=yes&amp;characterEncoding=UTF-8
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect 

Pojo

class User{
@Id
@Column(name = &quot;username&quot;, unique = true, nullable = false, length = 64)
private String username;
@Column(name = &quot;password&quot;)
private String password;
@Column(name = &quot;email&quot;, length = 100)
private String email;
//getter and setter
//to string()
}

mysql table property

CREATE TABLE `User` (
`username` varchar(64) CHARACTER SET utf8 NOT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

When am saving arabic characters it save successfully in database.

But when am fetching am getting ???? like this. when i debug and stopped at that point i see it get Arabic fonts correctly on that object.

如何在Java中发送邮件时支持阿拉伯语单词。

Email sending code

private void initSession() {
Properties props = new Properties();
props.setProperty(&quot;mail.smtp.host&quot;, &quot;smtp.gmail.com&quot;);
props.put(&quot;mail.smtp.auth&quot;, &quot;true&quot;);
props.put(&quot;mail.smtp.port&quot;, &quot;587&quot;);
props.setProperty(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;);
props.put(&quot;mail.smtp.socketFactory.port&quot;, &quot;587&quot;);
props.put(&quot;mail.smtp.socketFactory.class&quot;, &quot;javax.net.ssl.SSLSocketFactory&quot;);
//        props.put(&quot;mail.debug&quot;, &quot;true&quot;);
session = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
public String forgetPassword(String accounts, String e_address) {
EmailMessage emailMessage = new EmailMessage();
emailMessage.setSubject(&quot;Forget Password&quot;);
emailMessage.setBody(MessageTemplate.forgetPassword(accounts));
emailMessage.setTo_address(e_address);
try {
sendEmail(emailMessage);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return &quot;Successfully send&quot;;
}
private void sendmail(EmailMessage emailmessage) throws AddressException, MessagingException, IOException {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username, false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailmessage.getTo_address()));
msg.setSubject(emailmessage.getSubject());
msg.setContent(emailmessage.getBody(), &quot;text/html&quot;);
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(emailmessage.getBody(), &quot;text/html&quot;);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}

Service code

public String getAllAccount(String email) {
List&lt;User&gt; users = myUserRepository.findByEmail(email);
System.out.println(users.toString());
return users.toString();
}

Controller code

     @PostMapping(&quot;/forgetPassword&quot;)
public ResponseEntity forgetPassword(@RequestBody GetEmail getEmail) {
ResponseEntity responseEntity;
Map&lt;String, String&gt; result = new HashMap&lt;&gt;();
if (!PatternMatch.isValidEmail(getEmail.getEmail())) {
result.put(&quot;result&quot;, UserConstant.UNSUPPORTED_EMAIL + &quot;&quot;);
} else {
String accounts = service.getAllAccount(getEmail.getEmail());
System.out.println(&quot;accounts &quot; + accounts);
if (accounts.equals(&quot;&quot;)) {
result.put(&quot;result&quot;, UserConstant.EMAIL_NOT_EXISTS + &quot;&quot;);
} else {
new Thread(() -&gt; {
final EmailSender sender = EmailSender.getInstance();
sender.forgetPassword(accounts, getEmail.getEmail());
}) {
}.start();
result.put(&quot;result&quot;, UserConstant.EMAIL_SENT_SUCCESSFULLY + &quot;&quot;);
}
}

what am doing wrong please help me.

答案1

得分: 2

请检查您的控制台是否使用了UTF-8字符集,并设置您的电子邮件的字符集,例如:

msg.setContent(emailmessage.getBody(), "text/html;charset=utf-8");
英文:

Please check if your console is using the charset UTF-8 and set the charset of your e-mail, e.g. with:

msg.setContent(emailmessage.getBody(), &quot;text/html;charset=utf-8&quot;);

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

发表评论

匿名网友

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

确定