0

Trying to add an hyperlink(for email) in a MS Word document using docx module for Python.

I searched everywhere (official doc, StackOverflow, Google) but found nothing.

I would like to do something like:

from docx import Document

document = Document()   

p = document.add_paragraph('A plain paragraph')
p.add_hyperlink(mail_to:Joe_doe@email.com, Subject: The plain paragraph)

Anyone got an idea on how to do that?

Yflynn
  • 3
  • 3

1 Answers1

0

Reusing a function to add hyperlink from this answer,

First,we will form the "Mail To link" and then add it to the document as hyperlink like any-other hyperlink:-

#Necessary imports
from docx import Document
#Styling 
from docx.enum.dml import MSO_THEME_COLOR_INDEX
document=Document()
p = document.add_paragraph('A plain paragraph')

def add_hyperlink(paragraph, text, url):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink

#Define recipient and subject    
to_mail="John_doe@email.com"
subject="The plain paragraph"

mail_to_link=f"mailto:{to_mail}?Subject={subject}" 

#Adding the mail to link as any other hyperlink
add_hyperlink(p, 'Please Mail Us', mail_to_link)
document.save('mail_to_link_demo.docx')