简体   繁体   中英

Set sender name in JavaMailSender

I'm using JavaMailSender to send an email to my client by my gmail account. In my gmail account settings, I can set value to "Send mail as" in order to display my customize name in my client email. For example, if I send email in gmail, my client email will show this:

From: This is my customize name (not my email address)

To: client-email@mail.com

Subject ...

Body ...

How can I set up the configuration of JavaMailSender in Spring ?

This is my configuration file:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="myemailaddress@gmail.com" />
    <property name="password" value="mypassword@gmail.com" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
           </props>
    </property>
 </bean>

Thank in advance

To show email with a customized name showing in the inbox. I use MimeMessageHelper class from method. The one requiring two String parameters. It takes the email address and the customized name in this order

You need to use the MimeMessageHelper as suggested by mumbasa. You can configure it like

MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setTo(...);
message.setFrom("Your Site <info@your-site.com>");
message.setSubject(...);

Note how message.setFrom(String from) is actually being set. Instead of setting the from address to something like:

info@your-site.com

Set it to

Your Site <info@your-site.com>

Do to my exerience (using real e-mail clients) the sender of an e-mail message sent through Google mail cannot set the from address. It's always set by the Google servers according to the settings of your Gmail account. The client can provide whatever they want, Gmail won't care.

如果您使用的是SimpleMailMessage类(org.springframework.mail.SimpleMailMessage),您可以执行以下操作:

simpleMailMessage.setFrom("email@mail.com");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM