Search code examples
springgmailjakarta-mail

java mail - use dynamic sender email address


I am using email services (with my custom domain) from google. I want to use dynamic sender email address i.e. When user registers he should receive email from [email protected] and when he place order, should receive email from [email protected]

I have used java mail to send emails and application is developed using spring framework. Emails are sent, only issue they are always received from username specified in spring configuration xml.

Spring configuration:

<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="username" />
    <property name="password" value="password" />

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

MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(order.getCustomer().getEmailAddress()));
                mimeMessage.setFrom(new InternetAddress("[email protected]"));
                mimeMessage.setText(
                        "Dear " + order.getCustomer().getFirstName() + " "
                            + order.getCustomer().getLastName()
                            + ", thank you for placing order. Your order number is "
                            + order.getOrderNumber());
            }
        };

Any idea, where I am going wrong ?


Solution

  • Have you followed the Gmail instructions for sending from a different email address?