Search code examples
javaspring-bootjakarta-mail

Add title in send mail inside from.as like "Stack Overflow <[email protected]>"


I am not able to send mail to adding titles with from tab. I need to add the title and text with the mail as like "Stack Overflow <[email protected]>" How I will add the Stack Overflow title font of mail id.

My code is adding bellow

            String to = "[email protected]";
        String from = "[email protected]";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp-mail.outlook.com");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password");
            }
        });
        String msgBody = "test............";
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from, "NoReply"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, "Mr. Recipient"));
        msg.setSubject("Welcome To Java Mail API");
        msg.setText(msgBody);
        msg.setHeader("header_name", "header_value");
        Transport.send(msg);
        System.out.println("Email sent successfully...");
    }

Solution

  • You can simply use String from = "Rabin Samanta <[email protected]>";

    From the InternetAddress class documentation

    This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form "[email protected]" or "Personal Name <[email protected]>".

    https://docs.oracle.com/javaee/6/api/index.html?javax/mail/internet/InternetAddress.html


    What happens when you try this

    public static void main(String... args) throws Exception {
        Properties props = new Properties();
        props.put("mail.debug", "true");
        props.put("mail.smtp.host", "mail.smtpbucket.com");
        props.put("mail.smtp.port", "8025");
        props.put("mail.smtp.starttls.enable", "false");
        props.put("mail.smtp.auth", "false");
    
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setJavaMailProperties(props);
    
        MimeMessage msg1 = javaMailSender.createMimeMessage();
        MimeMessageHelper msg = new MimeMessageHelper(msg1, true);
        String from= "Me <[email protected]>";
        msg.setFrom(new InternetAddress(from));
        msg.setTo("Me <[email protected]>");
        msg.setText("Hello");
    
        javaMailSender.send(msg1);
    }
    

    And check the SMTP Bucket https://www.smtpbucket.com/[email protected]