Why am i unable to get the WeTransfer download links from an email?

I’m trying to write a script that finds emails from WeTransfer, downloads the attached files and deposits them to a directory on my computer. The code i have detects only one email from WeTransfer, says that the link is invalid and that it failed to extract download link. I’m stumped. Is my email parsing code somehow not correct?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import imaplib
import email
from email.header import decode_header
import requests
from bs4 import BeautifulSoup
import os
import shutil
from urllib.parse import urlparse, parse_qs
# Email credentials and IMAP server configuration for Yahoo Mail
EMAIL = 'xxxxxx.com'
PASSWORD = 'xxxxxx' # Use Yahoo account password or an App Password if you have 2FA enabled
IMAP_SERVER = 'imap.mail.yahoo.com'
IMAP_PORT = 993
# Define the folder to save the files
DOWNLOAD_DIR = '/home/JPW/Downloads'
ARCHIVE_DIR = '/home/JPW/archives'
def extract_download_link(we_transfer_url):
# Parse the WeTransfer URL
parsed_url = urlparse(we_transfer_url)
if parsed_url.hostname == 'wetransfer.com' and parsed_url.path.startswith('/downloads'):
# Extract the unique ID from the URL
unique_id = parsed_url.path.split('/')[-1]
# Construct the download URL using the unique ID
download_url = f"https://wetransfer.com/api/v4/transfers/{unique_id}/download"
return download_url
else:
print("Invalid WeTransfer URL. Only WeTransfer download links are supported.")
return None
def download_file(url, download_dir):
response = requests.get(url)
if response.status_code == 200:
filename = os.path.basename(url)
filepath = os.path.join(download_dir, filename)
with open(filepath, 'wb') as f:
f.write(response.content)
print("File downloaded successfully.")
return filepath
else:
print("Failed to download the file.")
return None
def move_file(src_path, dest_dir):
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
shutil.move(src_path, dest_dir)
def get_latest_wetransfer_link():
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
status, messages = mail.search(None, '(FROM "[email protected]")')
email_ids = messages[0].split()
if not email_ids:
print("No mails from Eugene found.")
return None
latest_email_id = email_ids[-1]
status, msg_data = mail.fetch(latest_email_id, '(RFC822)')
msg = email.message_from_bytes(msg_data[0][1])
mail.logout()
for part in msg.walk():
if part.get_content_type() == 'text/html':
html_content = part.get_payload(decode=True).decode()
soup = BeautifulSoup(html_content, 'html.parser')
all_links = soup.find_all('a', href=True)
for a in all_links:
if 'wetransfer.com/downloads' in a['href']:
print("WeTransfer link found:", a['href'])
return a['href']
print("No WeTransfer link found in the latest email.")
return None
if __name__ == "__main__":
link = get_latest_wetransfer_link()
if link:
download_link = extract_download_link(link) # Calling extract_download_link here
if download_link:
downloaded_file = download_file(download_link, DOWNLOAD_DIR)
if downloaded_file:
move_file(downloaded_file, ARCHIVE_DIR)
print(f"File moved to {ARCHIVE_DIR}")
else:
print("Failed to download the file.")
else:
print("Failed to extract download link.")
else:
print("No WeTransfer link found in the latest email.")
</code>
<code>import imaplib import email from email.header import decode_header import requests from bs4 import BeautifulSoup import os import shutil from urllib.parse import urlparse, parse_qs # Email credentials and IMAP server configuration for Yahoo Mail EMAIL = 'xxxxxx.com' PASSWORD = 'xxxxxx' # Use Yahoo account password or an App Password if you have 2FA enabled IMAP_SERVER = 'imap.mail.yahoo.com' IMAP_PORT = 993 # Define the folder to save the files DOWNLOAD_DIR = '/home/JPW/Downloads' ARCHIVE_DIR = '/home/JPW/archives' def extract_download_link(we_transfer_url): # Parse the WeTransfer URL parsed_url = urlparse(we_transfer_url) if parsed_url.hostname == 'wetransfer.com' and parsed_url.path.startswith('/downloads'): # Extract the unique ID from the URL unique_id = parsed_url.path.split('/')[-1] # Construct the download URL using the unique ID download_url = f"https://wetransfer.com/api/v4/transfers/{unique_id}/download" return download_url else: print("Invalid WeTransfer URL. Only WeTransfer download links are supported.") return None def download_file(url, download_dir): response = requests.get(url) if response.status_code == 200: filename = os.path.basename(url) filepath = os.path.join(download_dir, filename) with open(filepath, 'wb') as f: f.write(response.content) print("File downloaded successfully.") return filepath else: print("Failed to download the file.") return None def move_file(src_path, dest_dir): if not os.path.exists(dest_dir): os.makedirs(dest_dir) shutil.move(src_path, dest_dir) def get_latest_wetransfer_link(): mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) mail.login(EMAIL, PASSWORD) mail.select('inbox') status, messages = mail.search(None, '(FROM "[email protected]")') email_ids = messages[0].split() if not email_ids: print("No mails from Eugene found.") return None latest_email_id = email_ids[-1] status, msg_data = mail.fetch(latest_email_id, '(RFC822)') msg = email.message_from_bytes(msg_data[0][1]) mail.logout() for part in msg.walk(): if part.get_content_type() == 'text/html': html_content = part.get_payload(decode=True).decode() soup = BeautifulSoup(html_content, 'html.parser') all_links = soup.find_all('a', href=True) for a in all_links: if 'wetransfer.com/downloads' in a['href']: print("WeTransfer link found:", a['href']) return a['href'] print("No WeTransfer link found in the latest email.") return None if __name__ == "__main__": link = get_latest_wetransfer_link() if link: download_link = extract_download_link(link) # Calling extract_download_link here if download_link: downloaded_file = download_file(download_link, DOWNLOAD_DIR) if downloaded_file: move_file(downloaded_file, ARCHIVE_DIR) print(f"File moved to {ARCHIVE_DIR}") else: print("Failed to download the file.") else: print("Failed to extract download link.") else: print("No WeTransfer link found in the latest email.") </code>
import imaplib
import email
from email.header import decode_header
import requests
from bs4 import BeautifulSoup
import os
import shutil
from urllib.parse import urlparse, parse_qs

# Email credentials and IMAP server configuration for Yahoo Mail
EMAIL = 'xxxxxx.com'
PASSWORD = 'xxxxxx' # Use Yahoo account password or an App Password if you have 2FA enabled
IMAP_SERVER = 'imap.mail.yahoo.com'
IMAP_PORT = 993

# Define the folder to save the files
DOWNLOAD_DIR = '/home/JPW/Downloads'
ARCHIVE_DIR = '/home/JPW/archives'


def extract_download_link(we_transfer_url):
    # Parse the WeTransfer URL
    parsed_url = urlparse(we_transfer_url)
    if parsed_url.hostname == 'wetransfer.com' and parsed_url.path.startswith('/downloads'):
        # Extract the unique ID from the URL
        unique_id = parsed_url.path.split('/')[-1]
        # Construct the download URL using the unique ID
        download_url = f"https://wetransfer.com/api/v4/transfers/{unique_id}/download"
        return download_url
    else:
        print("Invalid WeTransfer URL. Only WeTransfer download links are supported.")
        return None


def download_file(url, download_dir):
    response = requests.get(url)
    if response.status_code == 200:
        filename = os.path.basename(url)
        filepath = os.path.join(download_dir, filename)
        with open(filepath, 'wb') as f:
            f.write(response.content)
        print("File downloaded successfully.")
        return filepath
    else:
        print("Failed to download the file.")
        return None

def move_file(src_path, dest_dir):
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    shutil.move(src_path, dest_dir)

def get_latest_wetransfer_link():
    mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
    mail.login(EMAIL, PASSWORD)
    mail.select('inbox')

    status, messages = mail.search(None, '(FROM "[email protected]")')
    email_ids = messages[0].split()

    if not email_ids:
        print("No mails from Eugene found.")
        return None

    latest_email_id = email_ids[-1]

    status, msg_data = mail.fetch(latest_email_id, '(RFC822)')
    msg = email.message_from_bytes(msg_data[0][1])

    mail.logout()

    for part in msg.walk():
        if part.get_content_type() == 'text/html':
            html_content = part.get_payload(decode=True).decode()
            soup = BeautifulSoup(html_content, 'html.parser')
            all_links = soup.find_all('a', href=True)
            for a in all_links:
                if 'wetransfer.com/downloads' in a['href']:
                    print("WeTransfer link found:", a['href'])
                    return a['href']
    print("No WeTransfer link found in the latest email.")
    return None

if __name__ == "__main__":
    link = get_latest_wetransfer_link()
    if link:
        download_link = extract_download_link(link)  # Calling extract_download_link here
        if download_link:
            downloaded_file = download_file(download_link, DOWNLOAD_DIR)
            if downloaded_file:
                move_file(downloaded_file, ARCHIVE_DIR)
                print(f"File moved to {ARCHIVE_DIR}")
            else:
                print("Failed to download the file.")
        else:
            print("Failed to extract download link.")
    else:
        print("No WeTransfer link found in the latest email.")

Thanks!

Jair-Rohm

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật